Add code to better handle unplugging of a reader.
[gnupg.git] / scd / apdu.c
blob36bae89c0b89265055386a8a168d62b9affa820f
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 "cardglue.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
59 #include "scdaemon.h"
60 #include "exechelp.h"
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
63 #include "apdu.h"
64 #include "ccid-driver.h"
67 /* Due to conflicting use of threading libraries we usually can't link
68 against libpcsclite. Instead we use a wrapper program. */
69 #ifdef USE_GNU_PTH
70 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
71 #define NEED_PCSC_WRAPPER 1
72 #endif
73 #endif
76 #define MAX_READER 4 /* Number of readers we support concurrently. */
79 #if defined(_WIN32) || defined(__CYGWIN__)
80 #define DLSTDCALL __stdcall
81 #else
82 #define DLSTDCALL
83 #endif
86 /* Helper to pass parameters related to keypad based operations. */
87 struct pininfo_s
89 int mode;
90 int minlen;
91 int maxlen;
92 int padlen;
95 /* A structure to collect information pertaining to one reader
96 slot. */
97 struct reader_table_s {
98 int used; /* True if slot is used. */
99 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
101 /* Function pointers intialized to the various backends. */
102 int (*connect_card)(int);
103 int (*disconnect_card)(int);
104 int (*close_reader)(int);
105 int (*shutdown_reader)(int);
106 int (*reset_reader)(int);
107 int (*get_status_reader)(int, unsigned int *);
108 int (*send_apdu_reader)(int,unsigned char *,size_t,
109 unsigned char *, size_t *, struct pininfo_s *);
110 int (*check_keypad)(int, int, int, int, int, int);
111 void (*dump_status_reader)(int);
112 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
114 struct {
115 ccid_driver_t handle;
116 } ccid;
117 struct {
118 unsigned long context;
119 unsigned long card;
120 unsigned long protocol;
121 #ifdef NEED_PCSC_WRAPPER
122 int req_fd;
123 int rsp_fd;
124 pid_t pid;
125 #endif /*NEED_PCSC_WRAPPER*/
126 } pcsc;
127 #ifdef USE_G10CODE_RAPDU
128 struct {
129 rapdu_t handle;
130 } rapdu;
131 #endif /*USE_G10CODE_RAPDU*/
132 char *rdrname; /* Name of the connected reader or NULL if unknown. */
133 int any_status; /* True if we have seen any status. */
134 int last_status;
135 int status;
136 int is_t0; /* True if we know that we are running T=0. */
137 unsigned char atr[33];
138 size_t atrlen; /* A zero length indicates that the ATR has
139 not yet been read; i.e. the card is not
140 ready for use. */
141 unsigned int change_counter;
142 #ifdef USE_GNU_PTH
143 int lock_initialized;
144 pth_mutex_t lock;
145 #endif
147 typedef struct reader_table_s *reader_table_t;
149 /* A global table to keep track of active readers. */
150 static struct reader_table_s reader_table[MAX_READER];
153 /* ct API function pointer. */
154 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
155 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
156 unsigned char *sad, unsigned short lc,
157 unsigned char *cmd, unsigned short *lr,
158 unsigned char *rsp);
159 static char (* DLSTDCALL CT_close) (unsigned short ctn);
161 /* PC/SC constants and function pointer. */
162 #define PCSC_SCOPE_USER 0
163 #define PCSC_SCOPE_TERMINAL 1
164 #define PCSC_SCOPE_SYSTEM 2
165 #define PCSC_SCOPE_GLOBAL 3
167 #define PCSC_PROTOCOL_T0 1
168 #define PCSC_PROTOCOL_T1 2
169 #define PCSC_PROTOCOL_RAW 4
171 #define PCSC_SHARE_EXCLUSIVE 1
172 #define PCSC_SHARE_SHARED 2
173 #define PCSC_SHARE_DIRECT 3
175 #define PCSC_LEAVE_CARD 0
176 #define PCSC_RESET_CARD 1
177 #define PCSC_UNPOWER_CARD 2
178 #define PCSC_EJECT_CARD 3
180 #define PCSC_UNKNOWN 0x0001
181 #define PCSC_ABSENT 0x0002 /* Card is absent. */
182 #define PCSC_PRESENT 0x0004 /* Card is present. */
183 #define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
184 #define PCSC_POWERED 0x0010 /* Card is powered. */
185 #define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
186 #define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
188 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
189 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
190 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
191 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
192 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
193 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
194 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
195 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
196 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
197 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
198 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
200 /* Some PC/SC error codes. */
201 #define PCSC_E_CANCELLED 0x80100002
202 #define PCSC_E_CANT_DISPOSE 0x8010000E
203 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
204 #define PCSC_E_INVALID_ATR 0x80100015
205 #define PCSC_E_INVALID_HANDLE 0x80100003
206 #define PCSC_E_INVALID_PARAMETER 0x80100004
207 #define PCSC_E_INVALID_TARGET 0x80100005
208 #define PCSC_E_INVALID_VALUE 0x80100011
209 #define PCSC_E_NO_MEMORY 0x80100006
210 #define PCSC_E_UNKNOWN_READER 0x80100009
211 #define PCSC_E_TIMEOUT 0x8010000A
212 #define PCSC_E_SHARING_VIOLATION 0x8010000B
213 #define PCSC_E_NO_SMARTCARD 0x8010000C
214 #define PCSC_E_UNKNOWN_CARD 0x8010000D
215 #define PCSC_E_PROTO_MISMATCH 0x8010000F
216 #define PCSC_E_NOT_READY 0x80100010
217 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
218 #define PCSC_E_NOT_TRANSACTED 0x80100016
219 #define PCSC_E_READER_UNAVAILABLE 0x80100017
220 #define PCSC_W_REMOVED_CARD 0x80100069
222 /* The PC/SC error is defined as a long as per specs. Due to left
223 shifts bit 31 will get sign extended. We use this mask to fix
224 it. */
225 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
228 struct pcsc_io_request_s
230 unsigned long protocol;
231 unsigned long pci_len;
234 typedef struct pcsc_io_request_s *pcsc_io_request_t;
236 struct pcsc_readerstate_s
238 const char *reader;
239 void *user_data;
240 unsigned long current_state;
241 unsigned long event_state;
242 unsigned long atrlen;
243 unsigned char atr[33];
246 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
248 long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
249 const void *reserved1,
250 const void *reserved2,
251 unsigned long *r_context);
252 long (* DLSTDCALL pcsc_release_context) (unsigned long context);
253 long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
254 const char *groups,
255 char *readers, unsigned long*readerslen);
256 long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
257 unsigned long timeout,
258 pcsc_readerstate_t readerstates,
259 unsigned long nreaderstates);
260 long (* DLSTDCALL pcsc_connect) (unsigned long context,
261 const char *reader,
262 unsigned long share_mode,
263 unsigned long preferred_protocols,
264 unsigned long *r_card,
265 unsigned long *r_active_protocol);
266 long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
267 unsigned long share_mode,
268 unsigned long preferred_protocols,
269 unsigned long initialization,
270 unsigned long *r_active_protocol);
271 long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
272 unsigned long disposition);
273 long (* DLSTDCALL pcsc_status) (unsigned long card,
274 char *reader, unsigned long *readerlen,
275 unsigned long *r_state,
276 unsigned long *r_protocol,
277 unsigned char *atr, unsigned long *atrlen);
278 long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
279 long (* DLSTDCALL pcsc_end_transaction) (unsigned long card,
280 unsigned long disposition);
281 long (* DLSTDCALL pcsc_transmit) (unsigned long card,
282 const pcsc_io_request_t send_pci,
283 const unsigned char *send_buffer,
284 unsigned long send_len,
285 pcsc_io_request_t recv_pci,
286 unsigned char *recv_buffer,
287 unsigned long *recv_len);
288 long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
289 unsigned long timeout);
292 /* Prototypes. */
293 static int pcsc_get_status (int slot, unsigned int *status);
294 static int reset_pcsc_reader (int slot);
295 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
296 unsigned int *status,
297 unsigned int *changed);
302 Helper
306 /* Find an unused reader slot for PORTSTR and put it into the reader
307 table. Return -1 on error or the index into the reader table. */
308 static int
309 new_reader_slot (void)
311 int i, reader = -1;
313 for (i=0; i < MAX_READER; i++)
315 if (!reader_table[i].used && reader == -1)
316 reader = i;
318 if (reader == -1)
320 log_error ("new_reader_slot: out of slots\n");
321 return -1;
323 #ifdef USE_GNU_PTH
324 if (!reader_table[reader].lock_initialized)
326 if (!pth_mutex_init (&reader_table[reader].lock))
328 log_error ("error initializing mutex: %s\n", strerror (errno));
329 return -1;
331 reader_table[reader].lock_initialized = 1;
333 #endif /*USE_GNU_PTH*/
334 reader_table[reader].connect_card = NULL;
335 reader_table[reader].disconnect_card = NULL;
336 reader_table[reader].close_reader = NULL;
337 reader_table[reader].shutdown_reader = NULL;
338 reader_table[reader].reset_reader = NULL;
339 reader_table[reader].get_status_reader = NULL;
340 reader_table[reader].send_apdu_reader = NULL;
341 reader_table[reader].check_keypad = NULL;
342 reader_table[reader].dump_status_reader = NULL;
343 reader_table[reader].set_progress_cb = NULL;
345 reader_table[reader].used = 1;
346 reader_table[reader].any_status = 0;
347 reader_table[reader].last_status = 0;
348 reader_table[reader].is_t0 = 1;
349 #ifdef NEED_PCSC_WRAPPER
350 reader_table[reader].pcsc.req_fd = -1;
351 reader_table[reader].pcsc.rsp_fd = -1;
352 reader_table[reader].pcsc.pid = (pid_t)(-1);
353 #endif
355 return reader;
359 static void
360 dump_reader_status (int slot)
362 if (!opt.verbose)
363 return;
365 if (reader_table[slot].dump_status_reader)
366 reader_table[slot].dump_status_reader (slot);
368 if (reader_table[slot].status != -1
369 && reader_table[slot].atrlen)
371 log_info ("slot %d: ATR=", slot);
372 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
378 static const char *
379 host_sw_string (long err)
381 switch (err)
383 case 0: return "okay";
384 case SW_HOST_OUT_OF_CORE: return "out of core";
385 case SW_HOST_INV_VALUE: return "invalid value";
386 case SW_HOST_NO_DRIVER: return "no driver";
387 case SW_HOST_NOT_SUPPORTED: return "not supported";
388 case SW_HOST_LOCKING_FAILED: return "locking failed";
389 case SW_HOST_BUSY: return "busy";
390 case SW_HOST_NO_CARD: return "no card";
391 case SW_HOST_CARD_INACTIVE: return "card inactive";
392 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
393 case SW_HOST_GENERAL_ERROR: return "general error";
394 case SW_HOST_NO_READER: return "no reader";
395 case SW_HOST_ABORTED: return "aborted";
396 case SW_HOST_NO_KEYPAD: return "no keypad";
397 case SW_HOST_ALREADY_CONNECTED: return "already connected";
398 default: return "unknown host status error";
403 const char *
404 apdu_strerror (int rc)
406 switch (rc)
408 case SW_EOF_REACHED : return "eof reached";
409 case SW_EEPROM_FAILURE : return "eeprom failure";
410 case SW_WRONG_LENGTH : return "wrong length";
411 case SW_CHV_WRONG : return "CHV wrong";
412 case SW_CHV_BLOCKED : return "CHV blocked";
413 case SW_USE_CONDITIONS : return "use conditions not satisfied";
414 case SW_BAD_PARAMETER : return "bad parameter";
415 case SW_NOT_SUPPORTED : return "not supported";
416 case SW_FILE_NOT_FOUND : return "file not found";
417 case SW_RECORD_NOT_FOUND:return "record not found";
418 case SW_REF_NOT_FOUND : return "reference not found";
419 case SW_BAD_LC : return "bad Lc";
420 case SW_BAD_P0_P1 : return "bad P0 or P1";
421 case SW_INS_NOT_SUP : return "instruction not supported";
422 case SW_CLA_NOT_SUP : return "class not supported";
423 case SW_SUCCESS : return "success";
424 default:
425 if ((rc & ~0x00ff) == SW_MORE_DATA)
426 return "more data available";
427 if ( (rc & 0x10000) )
428 return host_sw_string (rc);
429 return "unknown status error";
436 ct API Interface
439 static const char *
440 ct_error_string (long err)
442 switch (err)
444 case 0: return "okay";
445 case -1: return "invalid data";
446 case -8: return "ct error";
447 case -10: return "transmission error";
448 case -11: return "memory allocation error";
449 case -128: return "HTSI error";
450 default: return "unknown CT-API error";
455 static void
456 ct_dump_reader_status (int slot)
458 log_info ("reader slot %d: %s\n", slot,
459 reader_table[slot].status == 1? "Processor ICC present" :
460 reader_table[slot].status == 0? "Memory ICC present" :
461 "ICC not present" );
465 /* Wait for the card in SLOT and activate it. Return a status word
466 error or 0 on success. */
467 static int
468 ct_activate_card (int slot)
470 int rc;
471 unsigned char dad[1], sad[1], cmd[11], buf[256];
472 unsigned short buflen;
474 /* Check whether card has been inserted. */
475 dad[0] = 1; /* Destination address: CT. */
476 sad[0] = 2; /* Source address: Host. */
478 cmd[0] = 0x20; /* Class byte. */
479 cmd[1] = 0x13; /* Request status. */
480 cmd[2] = 0x00; /* From kernel. */
481 cmd[3] = 0x80; /* Return card's DO. */
482 cmd[4] = 0x00;
484 buflen = DIM(buf);
486 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
487 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
489 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
490 slot, ct_error_string (rc));
491 return SW_HOST_CARD_IO_ERROR;
494 /* Connected, now activate the card. */
495 dad[0] = 1; /* Destination address: CT. */
496 sad[0] = 2; /* Source address: Host. */
498 cmd[0] = 0x20; /* Class byte. */
499 cmd[1] = 0x12; /* Request ICC. */
500 cmd[2] = 0x01; /* From first interface. */
501 cmd[3] = 0x01; /* Return card's ATR. */
502 cmd[4] = 0x00;
504 buflen = DIM(buf);
506 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
507 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
509 log_error ("ct_activate_card(%d): activation failed: %s\n",
510 slot, ct_error_string (rc));
511 if (!rc)
512 log_printhex (" received data:", buf, buflen);
513 return SW_HOST_CARD_IO_ERROR;
516 /* Store the type and the ATR. */
517 if (buflen - 2 > DIM (reader_table[0].atr))
519 log_error ("ct_activate_card(%d): ATR too long\n", slot);
520 return SW_HOST_CARD_IO_ERROR;
523 reader_table[slot].status = buf[buflen - 1];
524 memcpy (reader_table[slot].atr, buf, buflen - 2);
525 reader_table[slot].atrlen = buflen - 2;
526 return 0;
530 static int
531 close_ct_reader (int slot)
533 CT_close (slot);
534 reader_table[slot].used = 0;
535 return 0;
538 static int
539 reset_ct_reader (int slot)
541 /* FIXME: Check is this is sufficient do do a reset. */
542 return ct_activate_card (slot);
546 static int
547 ct_get_status (int slot, unsigned int *status)
549 (void)slot;
550 /* The status we returned is wrong but we don't care becuase ctAPI
551 is not anymore required. */
552 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
553 return 0;
556 /* Actually send the APDU of length APDULEN to SLOT and return a
557 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
558 set to BUFLEN. Returns: CT API error code. */
559 static int
560 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
561 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
563 int rc;
564 unsigned char dad[1], sad[1];
565 unsigned short ctbuflen;
567 (void)pininfo;
569 /* If we don't have an ATR, we need to reset the reader first. */
570 if (!reader_table[slot].atrlen
571 && (rc = reset_ct_reader (slot)))
572 return rc;
574 dad[0] = 0; /* Destination address: Card. */
575 sad[0] = 2; /* Source address: Host. */
576 ctbuflen = *buflen;
577 if (DBG_CARD_IO)
578 log_printhex (" CT_data:", apdu, apdulen);
579 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
580 *buflen = ctbuflen;
582 return rc? SW_HOST_CARD_IO_ERROR: 0;
587 /* Open a reader and return an internal handle for it. PORT is a
588 non-negative value with the port number of the reader. USB readers
589 do have port numbers starting at 32769. */
590 static int
591 open_ct_reader (int port)
593 int rc, reader;
595 if (port < 0 || port > 0xffff)
597 log_error ("open_ct_reader: invalid port %d requested\n", port);
598 return -1;
600 reader = new_reader_slot ();
601 if (reader == -1)
602 return reader;
603 reader_table[reader].port = port;
605 rc = CT_init (reader, (unsigned short)port);
606 if (rc)
608 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
609 port, ct_error_string (rc));
610 reader_table[reader].used = 0;
611 return -1;
614 /* Only try to activate the card. */
615 rc = ct_activate_card (reader);
616 if (rc)
618 reader_table[reader].atrlen = 0;
619 rc = 0;
622 reader_table[reader].close_reader = close_ct_reader;
623 reader_table[reader].reset_reader = reset_ct_reader;
624 reader_table[reader].get_status_reader = ct_get_status;
625 reader_table[reader].send_apdu_reader = ct_send_apdu;
626 reader_table[reader].check_keypad = NULL;
627 reader_table[reader].dump_status_reader = ct_dump_reader_status;
629 dump_reader_status (reader);
630 return reader;
635 PC/SC Interface
638 #ifdef NEED_PCSC_WRAPPER
639 static int
640 writen (int fd, const void *buf, size_t nbytes)
642 size_t nleft = nbytes;
643 int nwritten;
645 /* log_printhex (" writen:", buf, nbytes); */
647 while (nleft > 0)
649 #ifdef USE_GNU_PTH
650 nwritten = pth_write (fd, buf, nleft);
651 #else
652 nwritten = write (fd, buf, nleft);
653 #endif
654 if (nwritten < 0 && errno == EINTR)
655 continue;
656 if (nwritten < 0)
657 return -1;
658 nleft -= nwritten;
659 buf = (const char*)buf + nwritten;
661 return 0;
664 /* Read up to BUFLEN bytes from FD and return the number of bytes
665 actually read in NREAD. Returns -1 on error or 0 on success. */
666 static int
667 readn (int fd, void *buf, size_t buflen, size_t *nread)
669 size_t nleft = buflen;
670 int n;
671 /* void *orig_buf = buf; */
673 while (nleft > 0)
675 #ifdef USE_GNU_PTH
676 # ifdef HAVE_W32_SYSTEM
677 # error Cannot use pth_read here because it expects a system HANDLE.
678 # endif
679 n = pth_read (fd, buf, nleft);
680 #else
681 n = read (fd, buf, nleft);
682 #endif
683 if (n < 0 && errno == EINTR)
684 continue;
685 if (n < 0)
686 return -1; /* read error. */
687 if (!n)
688 break; /* EOF */
689 nleft -= n;
690 buf = (char*)buf + n;
692 if (nread)
693 *nread = buflen - nleft;
695 /* log_printhex (" readn:", orig_buf, *nread); */
697 return 0;
699 #endif /*NEED_PCSC_WRAPPER*/
701 static const char *
702 pcsc_error_string (long err)
704 const char *s;
706 if (!err)
707 return "okay";
708 if ((err & 0x80100000) != 0x80100000)
709 return "invalid PC/SC error code";
710 err &= 0xffff;
711 switch (err)
713 case 0x0002: s = "cancelled"; break;
714 case 0x000e: s = "can't dispose"; break;
715 case 0x0008: s = "insufficient buffer"; break;
716 case 0x0015: s = "invalid ATR"; break;
717 case 0x0003: s = "invalid handle"; break;
718 case 0x0004: s = "invalid parameter"; break;
719 case 0x0005: s = "invalid target"; break;
720 case 0x0011: s = "invalid value"; break;
721 case 0x0006: s = "no memory"; break;
722 case 0x0013: s = "comm error"; break;
723 case 0x0001: s = "internal error"; break;
724 case 0x0014: s = "unknown error"; break;
725 case 0x0007: s = "waited too long"; break;
726 case 0x0009: s = "unknown reader"; break;
727 case 0x000a: s = "timeout"; break;
728 case 0x000b: s = "sharing violation"; break;
729 case 0x000c: s = "no smartcard"; break;
730 case 0x000d: s = "unknown card"; break;
731 case 0x000f: s = "proto mismatch"; break;
732 case 0x0010: s = "not ready"; break;
733 case 0x0012: s = "system cancelled"; break;
734 case 0x0016: s = "not transacted"; break;
735 case 0x0017: s = "reader unavailable"; break;
736 case 0x0065: s = "unsupported card"; break;
737 case 0x0066: s = "unresponsive card"; break;
738 case 0x0067: s = "unpowered card"; break;
739 case 0x0068: s = "reset card"; break;
740 case 0x0069: s = "removed card"; break;
741 case 0x006a: s = "inserted card"; break;
742 case 0x001f: s = "unsupported feature"; break;
743 case 0x0019: s = "PCI too small"; break;
744 case 0x001a: s = "reader unsupported"; break;
745 case 0x001b: s = "duplicate reader"; break;
746 case 0x001c: s = "card unsupported"; break;
747 case 0x001d: s = "no service"; break;
748 case 0x001e: s = "service stopped"; break;
749 default: s = "unknown PC/SC error code"; break;
751 return s;
754 /* Map PC/SC error codes to our special host status words. */
755 static int
756 pcsc_error_to_sw (long ec)
758 int rc;
760 switch ( PCSC_ERR_MASK (ec) )
762 case 0: rc = 0; break;
764 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
765 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
766 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
767 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
768 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
769 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
771 case PCSC_E_INVALID_TARGET:
772 case PCSC_E_INVALID_VALUE:
773 case PCSC_E_INVALID_HANDLE:
774 case PCSC_E_INVALID_PARAMETER:
775 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
777 default: rc = SW_HOST_GENERAL_ERROR; break;
780 return rc;
783 static void
784 dump_pcsc_reader_status (int slot)
786 if (reader_table[slot].pcsc.card)
788 log_info ("reader slot %d: active protocol:", slot);
789 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
790 log_printf (" T0");
791 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
792 log_printf (" T1");
793 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
794 log_printf (" raw");
795 log_printf ("\n");
797 else
798 log_info ("reader slot %d: not connected\n", slot);
802 #ifndef NEED_PCSC_WRAPPER
803 static int
804 pcsc_get_status_direct (int slot, unsigned int *status)
806 long err;
807 struct pcsc_readerstate_s rdrstates[1];
809 memset (rdrstates, 0, sizeof *rdrstates);
810 rdrstates[0].reader = reader_table[slot].rdrname;
811 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
812 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
814 rdrstates, 1);
815 if (err == PCSC_E_TIMEOUT)
816 err = 0; /* Timeout is no error error here. */
817 if (err)
819 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
820 pcsc_error_string (err), err);
821 return pcsc_error_to_sw (err);
824 /* log_debug */
825 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
826 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
827 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
828 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
829 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
830 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
831 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
832 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
833 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
834 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
835 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
837 *status = 0;
838 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
839 *status |= APDU_CARD_PRESENT;
840 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
841 *status |= APDU_CARD_ACTIVE;
842 #ifndef HAVE_W32_SYSTEM
843 /* We indicate a useful card if it is not in use by another
844 application. This is because we only use exclusive access
845 mode. */
846 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
847 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
848 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
849 *status |= APDU_CARD_USABLE;
850 #else
851 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
852 time when we are the only user (SCM SCR335) under Windows. */
853 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
854 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
855 *status |= APDU_CARD_USABLE;
856 #endif
858 return 0;
860 #endif /*!NEED_PCSC_WRAPPER*/
863 #ifdef NEED_PCSC_WRAPPER
864 static int
865 pcsc_get_status_wrapped (int slot, unsigned int *status)
867 long err;
868 reader_table_t slotp;
869 size_t len, full_len;
870 int i, n;
871 unsigned char msgbuf[9];
872 unsigned char buffer[16];
873 int sw = SW_HOST_CARD_IO_ERROR;
875 slotp = reader_table + slot;
877 if (slotp->pcsc.req_fd == -1
878 || slotp->pcsc.rsp_fd == -1
879 || slotp->pcsc.pid == (pid_t)(-1) )
881 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
882 return sw;
885 msgbuf[0] = 0x04; /* STATUS command. */
886 len = 0;
887 msgbuf[1] = (len >> 24);
888 msgbuf[2] = (len >> 16);
889 msgbuf[3] = (len >> 8);
890 msgbuf[4] = (len );
891 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
893 log_error ("error sending PC/SC STATUS request: %s\n",
894 strerror (errno));
895 goto command_failed;
898 /* Read the response. */
899 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
901 log_error ("error receiving PC/SC STATUS response: %s\n",
902 i? strerror (errno) : "premature EOF");
903 goto command_failed;
905 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
906 if (msgbuf[0] != 0x81 || len < 4)
908 log_error ("invalid response header from PC/SC received\n");
909 goto command_failed;
911 len -= 4; /* Already read the error code. */
912 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
913 | (msgbuf[7] << 8 ) | msgbuf[8]);
914 if (err)
916 log_error ("pcsc_status failed: %s (0x%lx)\n",
917 pcsc_error_string (err), err);
918 /* This is a proper error code, so return immediately. */
919 return pcsc_error_to_sw (err);
922 full_len = len;
924 /* The current version returns 3 words but we allow also for old
925 versions returning only 2 words. */
926 n = 12 < len ? 12 : len;
927 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
928 || (len != 8 && len != 12))
930 log_error ("error receiving PC/SC STATUS response: %s\n",
931 i? strerror (errno) : "premature EOF");
932 goto command_failed;
935 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
938 full_len -= len;
939 /* Newer versions of the wrapper might send more status bytes.
940 Read them. */
941 while (full_len)
943 unsigned char dummybuf[128];
945 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
946 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
948 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
949 i? strerror (errno) : "premature EOF");
950 goto command_failed;
952 full_len -= n;
955 /* We are lucky: The wrapper already returns the data in the
956 required format. */
957 *status = buffer[3];
958 return 0;
960 command_failed:
961 close (slotp->pcsc.req_fd);
962 close (slotp->pcsc.rsp_fd);
963 slotp->pcsc.req_fd = -1;
964 slotp->pcsc.rsp_fd = -1;
965 kill (slotp->pcsc.pid, SIGTERM);
966 slotp->pcsc.pid = (pid_t)(-1);
967 slotp->used = 0;
968 return sw;
970 #endif /*NEED_PCSC_WRAPPER*/
973 static int
974 pcsc_get_status (int slot, unsigned int *status)
976 #ifdef NEED_PCSC_WRAPPER
977 return pcsc_get_status_wrapped (slot, status);
978 #else
979 return pcsc_get_status_direct (slot, status);
980 #endif
984 #ifndef NEED_PCSC_WRAPPER
985 static int
986 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
987 unsigned char *buffer, size_t *buflen,
988 struct pininfo_s *pininfo)
990 long err;
991 struct pcsc_io_request_s send_pci;
992 unsigned long recv_len;
994 if (!reader_table[slot].atrlen
995 && (err = reset_pcsc_reader (slot)))
996 return err;
998 if (DBG_CARD_IO)
999 log_printhex (" PCSC_data:", apdu, apdulen);
1001 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1002 send_pci.protocol = PCSC_PROTOCOL_T1;
1003 else
1004 send_pci.protocol = PCSC_PROTOCOL_T0;
1005 send_pci.pci_len = sizeof send_pci;
1006 recv_len = *buflen;
1007 err = pcsc_transmit (reader_table[slot].pcsc.card,
1008 &send_pci, apdu, apdulen,
1009 NULL, buffer, &recv_len);
1010 *buflen = recv_len;
1011 if (err)
1012 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1013 pcsc_error_string (err), err);
1015 return pcsc_error_to_sw (err);
1017 #endif /*!NEED_PCSC_WRAPPER*/
1020 #ifdef NEED_PCSC_WRAPPER
1021 static int
1022 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1023 unsigned char *buffer, size_t *buflen,
1024 struct pininfo_s *pininfo)
1026 long err;
1027 reader_table_t slotp;
1028 size_t len, full_len;
1029 int i, n;
1030 unsigned char msgbuf[9];
1031 int sw = SW_HOST_CARD_IO_ERROR;
1033 (void)pininfo;
1035 if (!reader_table[slot].atrlen
1036 && (err = reset_pcsc_reader (slot)))
1037 return err;
1039 if (DBG_CARD_IO)
1040 log_printhex (" PCSC_data:", apdu, apdulen);
1042 slotp = reader_table + slot;
1044 if (slotp->pcsc.req_fd == -1
1045 || slotp->pcsc.rsp_fd == -1
1046 || slotp->pcsc.pid == (pid_t)(-1) )
1048 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1049 return sw;
1052 msgbuf[0] = 0x03; /* TRANSMIT command. */
1053 len = apdulen;
1054 msgbuf[1] = (len >> 24);
1055 msgbuf[2] = (len >> 16);
1056 msgbuf[3] = (len >> 8);
1057 msgbuf[4] = (len );
1058 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1059 || writen (slotp->pcsc.req_fd, apdu, len))
1061 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1062 strerror (errno));
1063 goto command_failed;
1066 /* Read the response. */
1067 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1069 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1070 i? strerror (errno) : "premature EOF");
1071 goto command_failed;
1073 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1074 if (msgbuf[0] != 0x81 || len < 4)
1076 log_error ("invalid response header from PC/SC received\n");
1077 goto command_failed;
1079 len -= 4; /* Already read the error code. */
1080 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1081 | (msgbuf[7] << 8 ) | msgbuf[8]);
1082 if (err)
1084 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1085 pcsc_error_string (err), err);
1086 return pcsc_error_to_sw (err);
1089 full_len = len;
1091 n = *buflen < len ? *buflen : len;
1092 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1094 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1095 i? strerror (errno) : "premature EOF");
1096 goto command_failed;
1098 *buflen = n;
1100 full_len -= len;
1101 if (full_len)
1103 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1104 err = SW_HOST_INV_VALUE;
1106 /* We need to read any rest of the response, to keep the
1107 protocol running. */
1108 while (full_len)
1110 unsigned char dummybuf[128];
1112 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1113 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1115 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1116 i? strerror (errno) : "premature EOF");
1117 goto command_failed;
1119 full_len -= n;
1122 return err;
1124 command_failed:
1125 close (slotp->pcsc.req_fd);
1126 close (slotp->pcsc.rsp_fd);
1127 slotp->pcsc.req_fd = -1;
1128 slotp->pcsc.rsp_fd = -1;
1129 kill (slotp->pcsc.pid, SIGTERM);
1130 slotp->pcsc.pid = (pid_t)(-1);
1131 slotp->used = 0;
1132 return sw;
1134 #endif /*NEED_PCSC_WRAPPER*/
1137 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1138 *BUFLEN data in BUFFER, the actual returned size will be stored at
1139 BUFLEN. Returns: A status word. */
1140 static int
1141 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1142 unsigned char *buffer, size_t *buflen,
1143 struct pininfo_s *pininfo)
1145 #ifdef NEED_PCSC_WRAPPER
1146 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1147 #else
1148 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1149 #endif
1153 #ifndef NEED_PCSC_WRAPPER
1154 static int
1155 close_pcsc_reader_direct (int slot)
1157 pcsc_release_context (reader_table[slot].pcsc.context);
1158 xfree (reader_table[slot].rdrname);
1159 reader_table[slot].rdrname = NULL;
1160 reader_table[slot].used = 0;
1161 return 0;
1163 #endif /*!NEED_PCSC_WRAPPER*/
1166 #ifdef NEED_PCSC_WRAPPER
1167 static int
1168 close_pcsc_reader_wrapped (int slot)
1170 long err;
1171 reader_table_t slotp;
1172 size_t len;
1173 int i;
1174 unsigned char msgbuf[9];
1176 slotp = reader_table + slot;
1178 if (slotp->pcsc.req_fd == -1
1179 || slotp->pcsc.rsp_fd == -1
1180 || slotp->pcsc.pid == (pid_t)(-1) )
1182 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1183 return 0;
1186 msgbuf[0] = 0x02; /* CLOSE command. */
1187 len = 0;
1188 msgbuf[1] = (len >> 24);
1189 msgbuf[2] = (len >> 16);
1190 msgbuf[3] = (len >> 8);
1191 msgbuf[4] = (len );
1192 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1194 log_error ("error sending PC/SC CLOSE request: %s\n",
1195 strerror (errno));
1196 goto command_failed;
1199 /* Read the response. */
1200 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1202 log_error ("error receiving PC/SC CLOSE response: %s\n",
1203 i? strerror (errno) : "premature EOF");
1204 goto command_failed;
1206 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1207 if (msgbuf[0] != 0x81 || len < 4)
1209 log_error ("invalid response header from PC/SC received\n");
1210 goto command_failed;
1212 len -= 4; /* Already read the error code. */
1213 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1214 | (msgbuf[7] << 8 ) | msgbuf[8]);
1215 if (err)
1216 log_error ("pcsc_close failed: %s (0x%lx)\n",
1217 pcsc_error_string (err), err);
1219 /* We will close the wrapper in any case - errors are merely
1220 informational. */
1222 command_failed:
1223 close (slotp->pcsc.req_fd);
1224 close (slotp->pcsc.rsp_fd);
1225 slotp->pcsc.req_fd = -1;
1226 slotp->pcsc.rsp_fd = -1;
1227 kill (slotp->pcsc.pid, SIGTERM);
1228 slotp->pcsc.pid = (pid_t)(-1);
1229 slotp->used = 0;
1230 return 0;
1232 #endif /*NEED_PCSC_WRAPPER*/
1235 static int
1236 close_pcsc_reader (int slot)
1238 #ifdef NEED_PCSC_WRAPPER
1239 return close_pcsc_reader_wrapped (slot);
1240 #else
1241 return close_pcsc_reader_direct (slot);
1242 #endif
1246 /* Connect a PC/SC card. */
1247 #ifndef NEED_PCSC_WRAPPER
1248 static int
1249 connect_pcsc_card (int slot)
1251 long err;
1253 assert (slot >= 0 && slot < MAX_READER);
1255 if (reader_table[slot].pcsc.card)
1256 return SW_HOST_ALREADY_CONNECTED;
1258 reader_table[slot].atrlen = 0;
1259 reader_table[slot].last_status = 0;
1260 reader_table[slot].is_t0 = 0;
1262 err = pcsc_connect (reader_table[slot].pcsc.context,
1263 reader_table[slot].rdrname,
1264 PCSC_SHARE_EXCLUSIVE,
1265 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1266 &reader_table[slot].pcsc.card,
1267 &reader_table[slot].pcsc.protocol);
1268 if (err)
1270 reader_table[slot].pcsc.card = 0;
1271 if (err != PCSC_E_NO_SMARTCARD)
1272 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1273 pcsc_error_string (err), err);
1275 else
1277 char reader[250];
1278 unsigned long readerlen, atrlen;
1279 unsigned long card_state, card_protocol;
1281 atrlen = DIM (reader_table[0].atr);
1282 readerlen = sizeof reader -1 ;
1283 err = pcsc_status (reader_table[slot].pcsc.card,
1284 reader, &readerlen,
1285 &card_state, &card_protocol,
1286 reader_table[slot].atr, &atrlen);
1287 if (err)
1288 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1289 pcsc_error_string (err), err, readerlen);
1290 else
1292 if (atrlen > DIM (reader_table[0].atr))
1293 log_bug ("ATR returned by pcsc_status is too large\n");
1294 reader_table[slot].atrlen = atrlen;
1295 /* If we got to here we know that a card is present
1296 and usable. Remember this. */
1297 reader_table[slot].last_status = ( APDU_CARD_USABLE
1298 | APDU_CARD_PRESENT
1299 | APDU_CARD_ACTIVE);
1300 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1304 dump_reader_status (slot);
1305 return pcsc_error_to_sw (err);
1307 #endif /*!NEED_PCSC_WRAPPER*/
1310 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1311 is not connected. */
1312 #ifndef NEED_PCSC_WRAPPER
1313 static int
1314 disconnect_pcsc_card (int slot)
1316 long err;
1318 assert (slot >= 0 && slot < MAX_READER);
1320 if (!reader_table[slot].pcsc.card)
1321 return 0;
1323 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1324 if (err)
1326 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1327 pcsc_error_string (err), err);
1328 return SW_HOST_CARD_IO_ERROR;
1330 reader_table[slot].pcsc.card = 0;
1331 return 0;
1333 #endif /*!NEED_PCSC_WRAPPER*/
1336 #ifndef NEED_PCSC_WRAPPER
1337 static int
1338 reset_pcsc_reader_direct (int slot)
1340 int sw;
1342 sw = disconnect_pcsc_card (slot);
1343 if (!sw)
1344 sw = connect_pcsc_card (slot);
1346 return sw;
1348 #endif /*NEED_PCSC_WRAPPER*/
1351 #ifdef NEED_PCSC_WRAPPER
1352 static int
1353 reset_pcsc_reader_wrapped (int slot)
1355 long err;
1356 reader_table_t slotp;
1357 size_t len;
1358 int i, n;
1359 unsigned char msgbuf[9];
1360 unsigned int dummy_status;
1361 int sw = SW_HOST_CARD_IO_ERROR;
1363 slotp = reader_table + slot;
1365 if (slotp->pcsc.req_fd == -1
1366 || slotp->pcsc.rsp_fd == -1
1367 || slotp->pcsc.pid == (pid_t)(-1) )
1369 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1370 return sw;
1373 msgbuf[0] = 0x05; /* RESET command. */
1374 len = 0;
1375 msgbuf[1] = (len >> 24);
1376 msgbuf[2] = (len >> 16);
1377 msgbuf[3] = (len >> 8);
1378 msgbuf[4] = (len );
1379 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1381 log_error ("error sending PC/SC RESET request: %s\n",
1382 strerror (errno));
1383 goto command_failed;
1386 /* Read the response. */
1387 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1389 log_error ("error receiving PC/SC RESET response: %s\n",
1390 i? strerror (errno) : "premature EOF");
1391 goto command_failed;
1393 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1394 if (msgbuf[0] != 0x81 || len < 4)
1396 log_error ("invalid response header from PC/SC received\n");
1397 goto command_failed;
1399 len -= 4; /* Already read the error code. */
1400 if (len > DIM (slotp->atr))
1402 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1403 (unsigned long)len);
1404 sw = SW_HOST_GENERAL_ERROR;
1405 goto command_failed;
1407 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1408 | (msgbuf[7] << 8 ) | msgbuf[8]);
1409 if (err)
1411 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1412 pcsc_error_string (err), err);
1413 /* If the error code is no smart card, we should not considere
1414 this a major error and close the wrapper. */
1415 sw = pcsc_error_to_sw (err);
1416 if (err == PCSC_E_NO_SMARTCARD)
1417 return sw;
1418 goto command_failed;
1421 /* The open function may return a zero for the ATR length to
1422 indicate that no card is present. */
1423 n = len;
1424 if (n)
1426 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1428 log_error ("error receiving PC/SC RESET response: %s\n",
1429 i? strerror (errno) : "premature EOF");
1430 goto command_failed;
1433 slotp->atrlen = len;
1435 /* Read the status so that IS_T0 will be set. */
1436 pcsc_get_status (slot, &dummy_status);
1438 return 0;
1440 command_failed:
1441 close (slotp->pcsc.req_fd);
1442 close (slotp->pcsc.rsp_fd);
1443 slotp->pcsc.req_fd = -1;
1444 slotp->pcsc.rsp_fd = -1;
1445 kill (slotp->pcsc.pid, SIGTERM);
1446 slotp->pcsc.pid = (pid_t)(-1);
1447 slotp->used = 0;
1448 return sw;
1450 #endif /* !NEED_PCSC_WRAPPER */
1453 /* Send an PC/SC reset command and return a status word on error or 0
1454 on success. */
1455 static int
1456 reset_pcsc_reader (int slot)
1458 #ifdef NEED_PCSC_WRAPPER
1459 return reset_pcsc_reader_wrapped (slot);
1460 #else
1461 return reset_pcsc_reader_direct (slot);
1462 #endif
1466 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1467 error or a slot number for the reader. */
1468 #ifndef NEED_PCSC_WRAPPER
1469 static int
1470 open_pcsc_reader_direct (const char *portstr)
1472 long err;
1473 int slot;
1474 char *list = NULL;
1475 unsigned long nreader, listlen;
1476 char *p;
1478 slot = new_reader_slot ();
1479 if (slot == -1)
1480 return -1;
1482 /* Fixme: Allocating a context for each slot is not required. One
1483 global context should be sufficient. */
1484 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1485 &reader_table[slot].pcsc.context);
1486 if (err)
1488 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1489 pcsc_error_string (err), err);
1490 reader_table[slot].used = 0;
1491 return -1;
1494 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1495 NULL, NULL, &nreader);
1496 if (!err)
1498 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1499 if (!list)
1501 log_error ("error allocating memory for reader list\n");
1502 pcsc_release_context (reader_table[slot].pcsc.context);
1503 reader_table[slot].used = 0;
1504 return -1 /*SW_HOST_OUT_OF_CORE*/;
1506 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1507 NULL, list, &nreader);
1509 if (err)
1511 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1512 pcsc_error_string (err), err);
1513 pcsc_release_context (reader_table[slot].pcsc.context);
1514 reader_table[slot].used = 0;
1515 xfree (list);
1516 return -1;
1519 listlen = nreader;
1520 p = list;
1521 while (nreader)
1523 if (!*p && !p[1])
1524 break;
1525 if (*p)
1526 log_info ("detected reader `%s'\n", p);
1527 if (nreader < (strlen (p)+1))
1529 log_error ("invalid response from pcsc_list_readers\n");
1530 break;
1532 nreader -= strlen (p)+1;
1533 p += strlen (p) + 1;
1536 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1537 if (!reader_table[slot].rdrname)
1539 log_error ("error allocating memory for reader name\n");
1540 pcsc_release_context (reader_table[slot].pcsc.context);
1541 reader_table[slot].used = 0;
1542 return -1;
1544 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1545 xfree (list);
1546 list = NULL;
1548 reader_table[slot].pcsc.card = 0;
1549 reader_table[slot].atrlen = 0;
1550 reader_table[slot].last_status = 0;
1552 reader_table[slot].connect_card = connect_pcsc_card;
1553 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1554 reader_table[slot].close_reader = close_pcsc_reader;
1555 reader_table[slot].reset_reader = reset_pcsc_reader;
1556 reader_table[slot].get_status_reader = pcsc_get_status;
1557 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1558 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1560 dump_reader_status (slot);
1561 return slot;
1563 #endif /*!NEED_PCSC_WRAPPER */
1566 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1567 needed to cope with different thread models and other peculiarities
1568 of libpcsclite. */
1569 #ifdef NEED_PCSC_WRAPPER
1570 static int
1571 open_pcsc_reader_wrapped (const char *portstr)
1573 int slot;
1574 reader_table_t slotp;
1575 int fd, rp[2], wp[2];
1576 int n, i;
1577 pid_t pid;
1578 size_t len;
1579 unsigned char msgbuf[9];
1580 int err;
1581 unsigned int dummy_status;
1582 int sw = SW_HOST_CARD_IO_ERROR;
1583 /* Note that we use the constant and not the fucntion because this
1584 code won't be be used under Windows. */
1585 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1587 if (access (wrapperpgm, X_OK))
1589 log_error ("can't run PC/SC access module `%s': %s\n",
1590 wrapperpgm, strerror (errno));
1591 return -1;
1594 slot = new_reader_slot ();
1595 if (slot == -1)
1596 return -1;
1597 slotp = reader_table + slot;
1599 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
1600 the common directy but implement it directly so that this file
1601 may still be source copied. */
1603 if (pipe (rp) == -1)
1605 log_error ("error creating a pipe: %s\n", strerror (errno));
1606 slotp->used = 0;
1607 return -1;
1609 if (pipe (wp) == -1)
1611 log_error ("error creating a pipe: %s\n", strerror (errno));
1612 close (rp[0]);
1613 close (rp[1]);
1614 slotp->used = 0;
1615 return -1;
1618 pid = fork ();
1619 if (pid == -1)
1621 log_error ("error forking process: %s\n", strerror (errno));
1622 close (rp[0]);
1623 close (rp[1]);
1624 close (wp[0]);
1625 close (wp[1]);
1626 slotp->used = 0;
1627 return -1;
1629 slotp->pcsc.pid = pid;
1631 if (!pid)
1632 { /*
1633 === Child ===
1636 /* Double fork. */
1637 pid = fork ();
1638 if (pid == -1)
1639 _exit (31);
1640 if (pid)
1641 _exit (0); /* Immediate exit this parent, so that the child
1642 gets cleaned up by the init process. */
1644 /* Connect our pipes. */
1645 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1646 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1647 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1648 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1650 /* Send stderr to the bit bucket. */
1651 fd = open ("/dev/null", O_WRONLY);
1652 if (fd == -1)
1653 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1654 if (fd != 2 && dup2 (fd, 2) == -1)
1655 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1657 /* Close all other files. */
1658 close_all_fds (3, NULL);
1660 execl (wrapperpgm,
1661 "pcsc-wrapper",
1662 "--",
1663 "1", /* API version */
1664 opt.pcsc_driver, /* Name of the PC/SC library. */
1665 NULL);
1666 _exit (31);
1670 === Parent ===
1672 close (wp[0]);
1673 close (rp[1]);
1674 slotp->pcsc.req_fd = wp[1];
1675 slotp->pcsc.rsp_fd = rp[0];
1677 /* Wait for the intermediate child to terminate. */
1678 #ifdef USE_GNU_PTH
1679 #define WAIT pth_waitpid
1680 #else
1681 #define WAIT waitpid
1682 #endif
1683 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1685 #undef WAIT
1687 /* Now send the open request. */
1688 msgbuf[0] = 0x01; /* OPEN command. */
1689 len = portstr? strlen (portstr):0;
1690 msgbuf[1] = (len >> 24);
1691 msgbuf[2] = (len >> 16);
1692 msgbuf[3] = (len >> 8);
1693 msgbuf[4] = (len );
1694 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1695 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1697 log_error ("error sending PC/SC OPEN request: %s\n",
1698 strerror (errno));
1699 goto command_failed;
1701 /* Read the response. */
1702 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1704 log_error ("error receiving PC/SC OPEN response: %s\n",
1705 i? strerror (errno) : "premature EOF");
1706 goto command_failed;
1708 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1709 if (msgbuf[0] != 0x81 || len < 4)
1711 log_error ("invalid response header from PC/SC received\n");
1712 goto command_failed;
1714 len -= 4; /* Already read the error code. */
1715 if (len > DIM (slotp->atr))
1717 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1718 (unsigned long)len);
1719 goto command_failed;
1721 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1722 | (msgbuf[7] << 8 ) | msgbuf[8]);
1723 if (err)
1725 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1726 sw = pcsc_error_to_sw (err);
1727 goto command_failed;
1730 slotp->last_status = 0;
1732 /* The open request may return a zero for the ATR length to
1733 indicate that no card is present. */
1734 n = len;
1735 if (n)
1737 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1739 log_error ("error receiving PC/SC OPEN response: %s\n",
1740 i? strerror (errno) : "premature EOF");
1741 goto command_failed;
1743 /* If we got to here we know that a card is present
1744 and usable. Thus remember this. */
1745 slotp->last_status = ( APDU_CARD_USABLE
1746 | APDU_CARD_PRESENT
1747 | APDU_CARD_ACTIVE);
1749 slotp->atrlen = len;
1751 reader_table[slot].close_reader = close_pcsc_reader;
1752 reader_table[slot].reset_reader = reset_pcsc_reader;
1753 reader_table[slot].get_status_reader = pcsc_get_status;
1754 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1755 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1757 /* Read the status so that IS_T0 will be set. */
1758 pcsc_get_status (slot, &dummy_status);
1760 dump_reader_status (slot);
1761 return slot;
1763 command_failed:
1764 close (slotp->pcsc.req_fd);
1765 close (slotp->pcsc.rsp_fd);
1766 slotp->pcsc.req_fd = -1;
1767 slotp->pcsc.rsp_fd = -1;
1768 kill (slotp->pcsc.pid, SIGTERM);
1769 slotp->pcsc.pid = (pid_t)(-1);
1770 slotp->used = 0;
1771 /* There is no way to return SW. */
1772 return -1;
1775 #endif /*NEED_PCSC_WRAPPER*/
1778 static int
1779 open_pcsc_reader (const char *portstr)
1781 #ifdef NEED_PCSC_WRAPPER
1782 return open_pcsc_reader_wrapped (portstr);
1783 #else
1784 return open_pcsc_reader_direct (portstr);
1785 #endif
1790 #ifdef HAVE_LIBUSB
1792 Internal CCID driver interface.
1796 static void
1797 dump_ccid_reader_status (int slot)
1799 log_info ("reader slot %d: using ccid driver\n", slot);
1802 static int
1803 close_ccid_reader (int slot)
1805 ccid_close_reader (reader_table[slot].ccid.handle);
1806 reader_table[slot].used = 0;
1807 return 0;
1811 static int
1812 shutdown_ccid_reader (int slot)
1814 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1815 return 0;
1819 static int
1820 reset_ccid_reader (int slot)
1822 int err;
1823 reader_table_t slotp = reader_table + slot;
1824 unsigned char atr[33];
1825 size_t atrlen;
1827 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1828 if (err)
1829 return err;
1830 /* If the reset was successful, update the ATR. */
1831 assert (sizeof slotp->atr >= sizeof atr);
1832 slotp->atrlen = atrlen;
1833 memcpy (slotp->atr, atr, atrlen);
1834 dump_reader_status (slot);
1835 return 0;
1839 static int
1840 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1842 reader_table_t slotp = reader_table + slot;
1844 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1848 static int
1849 get_status_ccid (int slot, unsigned int *status)
1851 int rc;
1852 int bits;
1854 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1855 if (rc)
1856 return rc;
1858 if (bits == 0)
1859 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1860 else if (bits == 1)
1861 *status = APDU_CARD_PRESENT;
1862 else
1863 *status = 0;
1865 return 0;
1869 /* Actually send the APDU of length APDULEN to SLOT and return a
1870 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1871 set to BUFLEN. Returns: Internal CCID driver error code. */
1872 static int
1873 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1874 unsigned char *buffer, size_t *buflen,
1875 struct pininfo_s *pininfo)
1877 long err;
1878 size_t maxbuflen;
1880 /* If we don't have an ATR, we need to reset the reader first. */
1881 if (!reader_table[slot].atrlen
1882 && (err = reset_ccid_reader (slot)))
1883 return err;
1885 if (DBG_CARD_IO)
1886 log_printhex (" raw apdu:", apdu, apdulen);
1888 maxbuflen = *buflen;
1889 if (pininfo)
1890 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1891 apdu, apdulen,
1892 pininfo->mode,
1893 pininfo->minlen,
1894 pininfo->maxlen,
1895 pininfo->padlen,
1896 buffer, maxbuflen, buflen);
1897 else
1898 err = ccid_transceive (reader_table[slot].ccid.handle,
1899 apdu, apdulen,
1900 buffer, maxbuflen, buflen);
1901 if (err)
1902 log_error ("ccid_transceive failed: (0x%lx)\n",
1903 err);
1905 return err;
1909 /* Check whether the CCID reader supports the ISO command code COMMAND
1910 on the keypad. Return 0 on success. For a description of the pin
1911 parameters, see ccid-driver.c */
1912 static int
1913 check_ccid_keypad (int slot, int command, int pin_mode,
1914 int pinlen_min, int pinlen_max, int pin_padlen)
1916 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1918 apdu[1] = command;
1919 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1920 apdu, sizeof apdu,
1921 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1922 NULL, 0, NULL);
1926 /* Open the reader and try to read an ATR. */
1927 static int
1928 open_ccid_reader (const char *portstr)
1930 int err;
1931 int slot;
1932 reader_table_t slotp;
1934 slot = new_reader_slot ();
1935 if (slot == -1)
1936 return -1;
1937 slotp = reader_table + slot;
1939 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1940 if (err)
1942 slotp->used = 0;
1943 return -1;
1946 err = ccid_get_atr (slotp->ccid.handle,
1947 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1948 if (err)
1950 slotp->atrlen = 0;
1951 err = 0;
1953 else
1955 /* If we got to here we know that a card is present
1956 and usable. Thus remember this. */
1957 reader_table[slot].last_status = (APDU_CARD_USABLE
1958 | APDU_CARD_PRESENT
1959 | APDU_CARD_ACTIVE);
1962 reader_table[slot].close_reader = close_ccid_reader;
1963 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1964 reader_table[slot].reset_reader = reset_ccid_reader;
1965 reader_table[slot].get_status_reader = get_status_ccid;
1966 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1967 reader_table[slot].check_keypad = check_ccid_keypad;
1968 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1969 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
1970 /* Our CCID reader code does not support T=0 at all, thus reset the
1971 flag. */
1972 reader_table[slot].is_t0 = 0;
1974 dump_reader_status (slot);
1975 return slot;
1980 #endif /* HAVE_LIBUSB */
1984 #ifdef USE_G10CODE_RAPDU
1986 The Remote APDU Interface.
1988 This uses the Remote APDU protocol to contact a reader.
1990 The port number is actually an index into the list of ports as
1991 returned via the protocol.
1995 static int
1996 rapdu_status_to_sw (int status)
1998 int rc;
2000 switch (status)
2002 case RAPDU_STATUS_SUCCESS: rc = 0; break;
2004 case RAPDU_STATUS_INVCMD:
2005 case RAPDU_STATUS_INVPROT:
2006 case RAPDU_STATUS_INVSEQ:
2007 case RAPDU_STATUS_INVCOOKIE:
2008 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
2010 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
2011 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2012 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2013 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2014 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2015 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2017 default: rc = SW_HOST_GENERAL_ERROR; break;
2020 return rc;
2025 static int
2026 close_rapdu_reader (int slot)
2028 rapdu_release (reader_table[slot].rapdu.handle);
2029 reader_table[slot].used = 0;
2030 return 0;
2034 static int
2035 reset_rapdu_reader (int slot)
2037 int err;
2038 reader_table_t slotp;
2039 rapdu_msg_t msg = NULL;
2041 slotp = reader_table + slot;
2043 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2044 if (err)
2046 log_error ("sending rapdu command RESET failed: %s\n",
2047 err < 0 ? strerror (errno): rapdu_strerror (err));
2048 rapdu_msg_release (msg);
2049 return rapdu_status_to_sw (err);
2051 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2052 if (err)
2054 log_error ("receiving rapdu message failed: %s\n",
2055 err < 0 ? strerror (errno): rapdu_strerror (err));
2056 rapdu_msg_release (msg);
2057 return rapdu_status_to_sw (err);
2059 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2061 int sw = rapdu_status_to_sw (msg->cmd);
2062 log_error ("rapdu command RESET failed: %s\n",
2063 rapdu_strerror (msg->cmd));
2064 rapdu_msg_release (msg);
2065 return sw;
2067 if (msg->datalen > DIM (slotp->atr))
2069 log_error ("ATR returned by the RAPDU layer is too large\n");
2070 rapdu_msg_release (msg);
2071 return SW_HOST_INV_VALUE;
2073 slotp->atrlen = msg->datalen;
2074 memcpy (slotp->atr, msg->data, msg->datalen);
2076 rapdu_msg_release (msg);
2077 return 0;
2081 static int
2082 my_rapdu_get_status (int slot, unsigned int *status)
2084 int err;
2085 reader_table_t slotp;
2086 rapdu_msg_t msg = NULL;
2087 int oldslot;
2089 slotp = reader_table + slot;
2091 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2092 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2093 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2094 if (err)
2096 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2097 err < 0 ? strerror (errno): rapdu_strerror (err));
2098 return rapdu_status_to_sw (err);
2100 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2101 if (err)
2103 log_error ("receiving rapdu message failed: %s\n",
2104 err < 0 ? strerror (errno): rapdu_strerror (err));
2105 rapdu_msg_release (msg);
2106 return rapdu_status_to_sw (err);
2108 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2110 int sw = rapdu_status_to_sw (msg->cmd);
2111 log_error ("rapdu command GET_STATUS failed: %s\n",
2112 rapdu_strerror (msg->cmd));
2113 rapdu_msg_release (msg);
2114 return sw;
2116 *status = msg->data[0];
2118 rapdu_msg_release (msg);
2119 return 0;
2123 /* Actually send the APDU of length APDULEN to SLOT and return a
2124 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2125 set to BUFLEN. Returns: APDU error code. */
2126 static int
2127 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2128 unsigned char *buffer, size_t *buflen,
2129 struct pininfo_s *pininfo)
2131 int err;
2132 reader_table_t slotp;
2133 rapdu_msg_t msg = NULL;
2134 size_t maxlen = *buflen;
2136 slotp = reader_table + slot;
2138 *buflen = 0;
2139 if (DBG_CARD_IO)
2140 log_printhex (" APDU_data:", apdu, apdulen);
2142 if (apdulen < 4)
2144 log_error ("rapdu_send_apdu: APDU is too short\n");
2145 return SW_HOST_INV_VALUE;
2148 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2149 if (err)
2151 log_error ("sending rapdu command APDU failed: %s\n",
2152 err < 0 ? strerror (errno): rapdu_strerror (err));
2153 rapdu_msg_release (msg);
2154 return rapdu_status_to_sw (err);
2156 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2157 if (err)
2159 log_error ("receiving rapdu message failed: %s\n",
2160 err < 0 ? strerror (errno): rapdu_strerror (err));
2161 rapdu_msg_release (msg);
2162 return rapdu_status_to_sw (err);
2164 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2166 int sw = rapdu_status_to_sw (msg->cmd);
2167 log_error ("rapdu command APDU failed: %s\n",
2168 rapdu_strerror (msg->cmd));
2169 rapdu_msg_release (msg);
2170 return sw;
2173 if (msg->datalen > maxlen)
2175 log_error ("rapdu response apdu too large\n");
2176 rapdu_msg_release (msg);
2177 return SW_HOST_INV_VALUE;
2180 *buflen = msg->datalen;
2181 memcpy (buffer, msg->data, msg->datalen);
2183 rapdu_msg_release (msg);
2184 return 0;
2187 static int
2188 open_rapdu_reader (int portno,
2189 const unsigned char *cookie, size_t length,
2190 int (*readfnc) (void *opaque,
2191 void *buffer, size_t size),
2192 void *readfnc_value,
2193 int (*writefnc) (void *opaque,
2194 const void *buffer, size_t size),
2195 void *writefnc_value,
2196 void (*closefnc) (void *opaque),
2197 void *closefnc_value)
2199 int err;
2200 int slot;
2201 reader_table_t slotp;
2202 rapdu_msg_t msg = NULL;
2204 slot = new_reader_slot ();
2205 if (slot == -1)
2206 return -1;
2207 slotp = reader_table + slot;
2209 slotp->rapdu.handle = rapdu_new ();
2210 if (!slotp->rapdu.handle)
2212 slotp->used = 0;
2213 return -1;
2216 rapdu_set_reader (slotp->rapdu.handle, portno);
2218 rapdu_set_iofunc (slotp->rapdu.handle,
2219 readfnc, readfnc_value,
2220 writefnc, writefnc_value,
2221 closefnc, closefnc_value);
2222 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2224 /* First try to get the current ATR, but if the card is inactive
2225 issue a reset instead. */
2226 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2227 if (err == RAPDU_STATUS_NEEDRESET)
2228 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2229 if (err)
2231 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2232 err < 0 ? strerror (errno): rapdu_strerror (err));
2233 goto failure;
2235 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2236 if (err)
2238 log_info ("receiving rapdu message failed: %s\n",
2239 err < 0 ? strerror (errno): rapdu_strerror (err));
2240 goto failure;
2242 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2244 log_info ("rapdu command GET ATR failed: %s\n",
2245 rapdu_strerror (msg->cmd));
2246 goto failure;
2248 if (msg->datalen > DIM (slotp->atr))
2250 log_error ("ATR returned by the RAPDU layer is too large\n");
2251 goto failure;
2253 slotp->atrlen = msg->datalen;
2254 memcpy (slotp->atr, msg->data, msg->datalen);
2256 reader_table[slot].close_reader = close_rapdu_reader;
2257 reader_table[slot].reset_reader = reset_rapdu_reader;
2258 reader_table[slot].get_status_reader = my_rapdu_get_status;
2259 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2260 reader_table[slot].check_keypad = NULL;
2261 reader_table[slot].dump_status_reader = NULL;
2263 dump_reader_status (slot);
2264 rapdu_msg_release (msg);
2265 return slot;
2267 failure:
2268 rapdu_msg_release (msg);
2269 rapdu_release (slotp->rapdu.handle);
2270 slotp->used = 0;
2271 return -1;
2274 #endif /*USE_G10CODE_RAPDU*/
2279 Driver Access
2283 static int
2284 lock_slot (int slot)
2286 #ifdef USE_GNU_PTH
2287 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2289 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2290 return SW_HOST_LOCKING_FAILED;
2292 #endif /*USE_GNU_PTH*/
2293 return 0;
2296 static int
2297 trylock_slot (int slot)
2299 #ifdef USE_GNU_PTH
2300 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2302 if (errno == EBUSY)
2303 return SW_HOST_BUSY;
2304 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2305 return SW_HOST_LOCKING_FAILED;
2307 #endif /*USE_GNU_PTH*/
2308 return 0;
2311 static void
2312 unlock_slot (int slot)
2314 #ifdef USE_GNU_PTH
2315 if (!pth_mutex_release (&reader_table[slot].lock))
2316 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2317 #endif /*USE_GNU_PTH*/
2321 /* Open the reader and return an internal slot number or -1 on
2322 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2323 the first USB reader. For PC/SC the first listed reader). */
2325 apdu_open_reader (const char *portstr)
2327 static int pcsc_api_loaded, ct_api_loaded;
2329 #ifdef HAVE_LIBUSB
2330 if (!opt.disable_ccid)
2332 int slot, i;
2333 const char *s;
2335 slot = open_ccid_reader (portstr);
2336 if (slot != -1)
2337 return slot; /* got one */
2339 /* If a CCID reader specification has been given, the user does
2340 not want a fallback to other drivers. */
2341 if (portstr)
2342 for (s=portstr, i=0; *s; s++)
2343 if (*s == ':' && (++i == 3))
2344 return -1;
2347 #endif /* HAVE_LIBUSB */
2349 if (opt.ctapi_driver && *opt.ctapi_driver)
2351 int port = portstr? atoi (portstr) : 32768;
2353 if (!ct_api_loaded)
2355 void *handle;
2357 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2358 if (!handle)
2360 log_error ("apdu_open_reader: failed to open driver: %s\n",
2361 dlerror ());
2362 return -1;
2364 CT_init = dlsym (handle, "CT_init");
2365 CT_data = dlsym (handle, "CT_data");
2366 CT_close = dlsym (handle, "CT_close");
2367 if (!CT_init || !CT_data || !CT_close)
2369 log_error ("apdu_open_reader: invalid CT-API driver\n");
2370 dlclose (handle);
2371 return -1;
2373 ct_api_loaded = 1;
2375 return open_ct_reader (port);
2379 /* No ctAPI configured, so lets try the PC/SC API */
2380 if (!pcsc_api_loaded)
2382 #ifndef NEED_PCSC_WRAPPER
2383 void *handle;
2385 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2386 if (!handle)
2388 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2389 opt.pcsc_driver, dlerror ());
2390 return -1;
2393 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2394 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2395 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2396 #if defined(_WIN32) || defined(__CYGWIN__)
2397 if (!pcsc_list_readers)
2398 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2399 #endif
2400 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2401 #if defined(_WIN32) || defined(__CYGWIN__)
2402 if (!pcsc_get_status_change)
2403 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2404 #endif
2405 pcsc_connect = dlsym (handle, "SCardConnect");
2406 #if defined(_WIN32) || defined(__CYGWIN__)
2407 if (!pcsc_connect)
2408 pcsc_connect = dlsym (handle, "SCardConnectA");
2409 #endif
2410 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2411 #if defined(_WIN32) || defined(__CYGWIN__)
2412 if (!pcsc_reconnect)
2413 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2414 #endif
2415 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2416 pcsc_status = dlsym (handle, "SCardStatus");
2417 #if defined(_WIN32) || defined(__CYGWIN__)
2418 if (!pcsc_status)
2419 pcsc_status = dlsym (handle, "SCardStatusA");
2420 #endif
2421 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2422 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2423 pcsc_transmit = dlsym (handle, "SCardTransmit");
2424 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2426 if (!pcsc_establish_context
2427 || !pcsc_release_context
2428 || !pcsc_list_readers
2429 || !pcsc_get_status_change
2430 || !pcsc_connect
2431 || !pcsc_reconnect
2432 || !pcsc_disconnect
2433 || !pcsc_status
2434 || !pcsc_begin_transaction
2435 || !pcsc_end_transaction
2436 || !pcsc_transmit
2437 /* || !pcsc_set_timeout */)
2439 /* Note that set_timeout is currently not used and also not
2440 available under Windows. */
2441 log_error ("apdu_open_reader: invalid PC/SC driver "
2442 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2443 !!pcsc_establish_context,
2444 !!pcsc_release_context,
2445 !!pcsc_list_readers,
2446 !!pcsc_get_status_change,
2447 !!pcsc_connect,
2448 !!pcsc_reconnect,
2449 !!pcsc_disconnect,
2450 !!pcsc_status,
2451 !!pcsc_begin_transaction,
2452 !!pcsc_end_transaction,
2453 !!pcsc_transmit,
2454 !!pcsc_set_timeout );
2455 dlclose (handle);
2456 return -1;
2458 #endif /*!NEED_PCSC_WRAPPER*/
2459 pcsc_api_loaded = 1;
2462 return open_pcsc_reader (portstr);
2466 /* Open an remote reader and return an internal slot number or -1 on
2467 error. This function is an alternative to apdu_open_reader and used
2468 with remote readers only. Note that the supplied CLOSEFNC will
2469 only be called once and the slot will not be valid afther this.
2471 If PORTSTR is NULL we default to the first availabe port.
2474 apdu_open_remote_reader (const char *portstr,
2475 const unsigned char *cookie, size_t length,
2476 int (*readfnc) (void *opaque,
2477 void *buffer, size_t size),
2478 void *readfnc_value,
2479 int (*writefnc) (void *opaque,
2480 const void *buffer, size_t size),
2481 void *writefnc_value,
2482 void (*closefnc) (void *opaque),
2483 void *closefnc_value)
2485 #ifdef USE_G10CODE_RAPDU
2486 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2487 cookie, length,
2488 readfnc, readfnc_value,
2489 writefnc, writefnc_value,
2490 closefnc, closefnc_value);
2491 #else
2492 (void)portstr;
2493 (void)cookie;
2494 (void)length;
2495 (void)readfnc;
2496 (void)readfnc_value;
2497 (void)writefnc;
2498 (void)writefnc_value;
2499 (void)closefnc;
2500 (void)closefnc_value;
2501 #ifdef _WIN32
2502 errno = ENOENT;
2503 #else
2504 errno = ENOSYS;
2505 #endif
2506 return -1;
2507 #endif
2512 apdu_close_reader (int slot)
2514 int sw;
2516 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2517 return SW_HOST_NO_DRIVER;
2518 sw = apdu_disconnect (slot);
2519 if (sw)
2520 return sw;
2521 if (reader_table[slot].close_reader)
2522 return reader_table[slot].close_reader (slot);
2523 return SW_HOST_NOT_SUPPORTED;
2527 /* Function suitable for a cleanup function to close all reader. It
2528 should not be used if the reader will be opened again. The reason
2529 for implementing this to properly close USB devices so that they
2530 will startup the next time without error. */
2531 void
2532 apdu_prepare_exit (void)
2534 static int sentinel;
2535 int slot;
2537 if (!sentinel)
2539 sentinel = 1;
2540 for (slot = 0; slot < MAX_READER; slot++)
2541 if (reader_table[slot].used)
2543 apdu_disconnect (slot);
2544 if (reader_table[slot].close_reader)
2545 reader_table[slot].close_reader (slot);
2546 reader_table[slot].used = 0;
2548 sentinel = 0;
2553 /* Shutdown a reader; that is basically the same as a close but keeps
2554 the handle ready for later use. A apdu_reset_reader or apdu_connect
2555 should be used to get it active again. */
2557 apdu_shutdown_reader (int slot)
2559 int sw;
2561 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2562 return SW_HOST_NO_DRIVER;
2563 sw = apdu_disconnect (slot);
2564 if (sw)
2565 return sw;
2566 if (reader_table[slot].shutdown_reader)
2567 return reader_table[slot].shutdown_reader (slot);
2568 return SW_HOST_NOT_SUPPORTED;
2571 /* Enumerate all readers and return information on whether this reader
2572 is in use. The caller should start with SLOT set to 0 and
2573 increment it with each call until an error is returned. */
2575 apdu_enum_reader (int slot, int *used)
2577 if (slot < 0 || slot >= MAX_READER)
2578 return SW_HOST_NO_DRIVER;
2579 *used = reader_table[slot].used;
2580 return 0;
2584 /* Connect a card. This is used to power up the card and make sure
2585 that an ATR is available. */
2587 apdu_connect (int slot)
2589 int sw;
2591 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2592 return SW_HOST_NO_DRIVER;
2594 /* Only if the access method provides a connect function we use it.
2595 If not, we expect that the card has been implicitly connected by
2596 apdu_open_reader. */
2597 if (reader_table[slot].connect_card)
2599 sw = lock_slot (slot);
2600 if (!sw)
2602 sw = reader_table[slot].connect_card (slot);
2603 unlock_slot (slot);
2606 else
2607 sw = 0;
2609 /* We need to call apdu_get_status_internal, so that the last-status
2610 machinery gets setup properly even if a card is inserted while
2611 scdaemon is fired up and apdu_get_status has not yet been called.
2612 Without that we would force a reset of the card with the next
2613 call to apdu_get_status. */
2614 apdu_get_status_internal (slot, 1, 1, NULL, NULL);
2616 return sw;
2621 apdu_disconnect (int slot)
2623 int sw;
2625 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2626 return SW_HOST_NO_DRIVER;
2628 if (reader_table[slot].disconnect_card)
2630 sw = lock_slot (slot);
2631 if (!sw)
2633 sw = reader_table[slot].disconnect_card (slot);
2634 unlock_slot (slot);
2637 else
2638 sw = 0;
2639 return sw;
2643 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
2644 CB is NULL the progress callback is removed. */
2646 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2648 int sw;
2650 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2651 return SW_HOST_NO_DRIVER;
2653 if (reader_table[slot].set_progress_cb)
2655 sw = lock_slot (slot);
2656 if (!sw)
2658 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2659 unlock_slot (slot);
2662 else
2663 sw = 0;
2664 return sw;
2668 /* Do a reset for the card in reader at SLOT. */
2670 apdu_reset (int slot)
2672 int sw;
2674 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2675 return SW_HOST_NO_DRIVER;
2677 if ((sw = lock_slot (slot)))
2678 return sw;
2680 reader_table[slot].last_status = 0;
2681 if (reader_table[slot].reset_reader)
2682 sw = reader_table[slot].reset_reader (slot);
2684 if (!sw)
2686 /* If we got to here we know that a card is present
2687 and usable. Thus remember this. */
2688 reader_table[slot].last_status = (APDU_CARD_USABLE
2689 | APDU_CARD_PRESENT
2690 | APDU_CARD_ACTIVE);
2693 unlock_slot (slot);
2694 return sw;
2698 /* Activate a card if it has not yet been done. This is a kind of
2699 reset-if-required. It is useful to test for presence of a card
2700 before issuing a bunch of apdu commands. It does not wait on a
2701 locked card. */
2703 apdu_activate (int slot)
2705 int sw;
2706 unsigned int s;
2708 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2709 return SW_HOST_NO_DRIVER;
2711 if ((sw = trylock_slot (slot)))
2712 return sw;
2714 if (reader_table[slot].get_status_reader)
2715 sw = reader_table[slot].get_status_reader (slot, &s);
2717 if (!sw)
2719 if (!(s & 2)) /* Card not present. */
2720 sw = SW_HOST_NO_CARD;
2721 else if ( ((s & 2) && !(s & 4))
2722 || !reader_table[slot].atrlen )
2724 /* We don't have an ATR or a card is present though inactive:
2725 do a reset now. */
2726 if (reader_table[slot].reset_reader)
2728 reader_table[slot].last_status = 0;
2729 sw = reader_table[slot].reset_reader (slot);
2730 if (!sw)
2732 /* If we got to here we know that a card is present
2733 and usable. Thus remember this. */
2734 reader_table[slot].last_status = (APDU_CARD_USABLE
2735 | APDU_CARD_PRESENT
2736 | APDU_CARD_ACTIVE);
2742 unlock_slot (slot);
2743 return sw;
2747 unsigned char *
2748 apdu_get_atr (int slot, size_t *atrlen)
2750 unsigned char *buf;
2752 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2753 return NULL;
2754 if (!reader_table[slot].atrlen)
2755 return NULL;
2756 buf = xtrymalloc (reader_table[slot].atrlen);
2757 if (!buf)
2758 return NULL;
2759 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2760 *atrlen = reader_table[slot].atrlen;
2761 return buf;
2766 /* Retrieve the status for SLOT. The function does only wait for the
2767 card to become available if HANG is set to true. On success the
2768 bits in STATUS will be set to
2770 APDU_CARD_USABLE (bit 0) = card present and usable
2771 APDU_CARD_PRESENT (bit 1) = card present
2772 APDU_CARD_ACTIVE (bit 2) = card active
2773 (bit 3) = card access locked [not yet implemented]
2775 For must applications, testing bit 0 is sufficient.
2777 CHANGED will receive the value of the counter tracking the number
2778 of card insertions. This value may be used to detect a card
2779 change.
2781 static int
2782 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
2783 unsigned int *status, unsigned int *changed)
2785 int sw;
2786 unsigned int s;
2788 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2789 return SW_HOST_NO_DRIVER;
2791 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2792 return sw;
2794 if (reader_table[slot].get_status_reader)
2795 sw = reader_table[slot].get_status_reader (slot, &s);
2797 unlock_slot (slot);
2799 if (sw)
2801 reader_table[slot].last_status = 0;
2802 return sw;
2805 /* Keep track of changes. */
2806 if (s != reader_table[slot].last_status
2807 || !reader_table[slot].any_status )
2809 reader_table[slot].change_counter++;
2810 /* Make sure that the ATR is invalid so that a reset will be
2811 triggered by apdu_activate. */
2812 if (!no_atr_reset)
2813 reader_table[slot].atrlen = 0;
2815 reader_table[slot].any_status = 1;
2816 reader_table[slot].last_status = s;
2818 if (status)
2819 *status = s;
2820 if (changed)
2821 *changed = reader_table[slot].change_counter;
2822 return 0;
2826 /* See above for a description. */
2828 apdu_get_status (int slot, int hang,
2829 unsigned int *status, unsigned int *changed)
2831 return apdu_get_status_internal (slot, hang, 0, status, changed);
2835 /* Check whether the reader supports the ISO command code COMMAND on
2836 the keypad. Return 0 on success. For a description of the pin
2837 parameters, see ccid-driver.c */
2839 apdu_check_keypad (int slot, int command, int pin_mode,
2840 int pinlen_min, int pinlen_max, int pin_padlen)
2842 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2843 return SW_HOST_NO_DRIVER;
2845 if (reader_table[slot].check_keypad)
2846 return reader_table[slot].check_keypad (slot, command,
2847 pin_mode, pinlen_min, pinlen_max,
2848 pin_padlen);
2849 else
2850 return SW_HOST_NOT_SUPPORTED;
2854 /* Dispatcher for the actual send_apdu function. Note, that this
2855 function should be called in locked state. */
2856 static int
2857 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2858 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2860 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2861 return SW_HOST_NO_DRIVER;
2863 if (reader_table[slot].send_apdu_reader)
2864 return reader_table[slot].send_apdu_reader (slot,
2865 apdu, apdulen,
2866 buffer, buflen,
2867 pininfo);
2868 else
2869 return SW_HOST_NOT_SUPPORTED;
2873 /* Core APDU tranceiver function. Parameters are described at
2874 apdu_send_le with the exception of PININFO which indicates keypad
2875 related operations if not NULL. If EXTENDED_MODE is not 0
2876 command chaining or extended length will be used according to these
2877 values:
2878 n < 0 := Use command chaining with the data part limited to -n
2879 in each chunk. If -1 is used a default value is used.
2880 n == 0 := No extended mode or command chaining.
2881 n == 1 := Use extended length for input and output without a
2882 length limit.
2883 n > 1 := Use extended length with up to N bytes.
2886 static int
2887 send_le (int slot, int class, int ins, int p0, int p1,
2888 int lc, const char *data, int le,
2889 unsigned char **retbuf, size_t *retbuflen,
2890 struct pininfo_s *pininfo, int extended_mode)
2892 #define SHORT_RESULT_BUFFER_SIZE 258
2893 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
2894 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2895 unsigned char *result_buffer = NULL;
2896 size_t result_buffer_size;
2897 unsigned char *result;
2898 size_t resultlen;
2899 unsigned char short_apdu_buffer[5+256+1];
2900 unsigned char *apdu_buffer = NULL;
2901 size_t apdu_buffer_size;
2902 unsigned char *apdu;
2903 size_t apdulen;
2904 int sw;
2905 long rc; /* We need a long here due to PC/SC. */
2906 int did_exact_length_hack = 0;
2907 int use_chaining = 0;
2908 int use_extended_length = 0;
2909 int lc_chunk;
2911 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2912 return SW_HOST_NO_DRIVER;
2914 if (DBG_CARD_IO)
2915 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2916 class, ins, p0, p1, lc, le, extended_mode);
2918 if (lc != -1 && (lc > 255 || lc < 0))
2920 /* Data does not fit into an APDU. What we do now depends on
2921 the EXTENDED_MODE parameter. */
2922 if (!extended_mode)
2923 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2924 else if (extended_mode > 0)
2925 use_extended_length = 1;
2926 else if (extended_mode < 0)
2928 /* Send APDU using chaining mode. */
2929 if (lc > 16384)
2930 return SW_WRONG_LENGTH; /* Sanity check. */
2931 if ((class&0xf0) != 0)
2932 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2933 use_chaining = extended_mode == -1? 255 : -extended_mode;
2934 use_chaining &= 0xff;
2936 else
2937 return SW_HOST_INV_VALUE;
2939 else if (lc == -1 && extended_mode > 0)
2940 use_extended_length = 1;
2942 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2944 /* Expected Data does not fit into an APDU. What we do now
2945 depends on the EXTENDED_MODE parameter. Note that a check
2946 for command chaining does not make sense because we are
2947 looking at Le. */
2948 if (!extended_mode)
2949 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2950 else if (use_extended_length)
2951 ; /* We are already using extended length. */
2952 else if (extended_mode > 0)
2953 use_extended_length = 1;
2954 else
2955 return SW_HOST_INV_VALUE;
2958 if ((!data && lc != -1) || (data && lc == -1))
2959 return SW_HOST_INV_VALUE;
2961 if (use_extended_length)
2963 if (reader_table[slot].is_t0)
2964 return SW_HOST_NOT_SUPPORTED;
2966 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2967 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2968 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2969 if (!apdu_buffer)
2970 return SW_HOST_OUT_OF_CORE;
2971 apdu = apdu_buffer;
2973 else
2975 apdu_buffer_size = sizeof short_apdu_buffer;
2976 apdu = short_apdu_buffer;
2979 if (use_extended_length && (le > 256 || le < 0))
2981 result_buffer_size = le < 0? 4096 : le;
2982 result_buffer = xtrymalloc (result_buffer_size + 10);
2983 if (!result_buffer)
2985 xfree (apdu_buffer);
2986 return SW_HOST_OUT_OF_CORE;
2988 result = result_buffer;
2990 else
2992 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2993 result = short_result_buffer;
2995 #undef SHORT_RESULT_BUFFER_SIZE
2997 if ((sw = lock_slot (slot)))
2999 xfree (apdu_buffer);
3000 xfree (result_buffer);
3001 return sw;
3006 if (use_extended_length)
3008 use_chaining = 0;
3009 apdulen = 0;
3010 apdu[apdulen++] = class;
3011 apdu[apdulen++] = ins;
3012 apdu[apdulen++] = p0;
3013 apdu[apdulen++] = p1;
3014 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3015 if (lc >= 0)
3017 apdu[apdulen++] = ((lc >> 8) & 0xff);
3018 apdu[apdulen++] = (lc & 0xff);
3019 memcpy (apdu+apdulen, data, lc);
3020 data += lc;
3021 apdulen += lc;
3023 if (le != -1)
3025 apdu[apdulen++] = ((le >> 8) & 0xff);
3026 apdu[apdulen++] = (le & 0xff);
3029 else
3031 apdulen = 0;
3032 apdu[apdulen] = class;
3033 if (use_chaining && lc > 255)
3035 apdu[apdulen] |= 0x10;
3036 assert (use_chaining < 256);
3037 lc_chunk = use_chaining;
3038 lc -= use_chaining;
3040 else
3042 use_chaining = 0;
3043 lc_chunk = lc;
3045 apdulen++;
3046 apdu[apdulen++] = ins;
3047 apdu[apdulen++] = p0;
3048 apdu[apdulen++] = p1;
3049 if (lc_chunk != -1)
3051 apdu[apdulen++] = lc_chunk;
3052 memcpy (apdu+apdulen, data, lc_chunk);
3053 data += lc_chunk;
3054 apdulen += lc_chunk;
3055 /* T=0 does not allow the use of Lc together with Le;
3056 thus disable Le in this case. */
3057 if (reader_table[slot].is_t0)
3058 le = -1;
3060 if (le != -1 && !use_chaining)
3061 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3064 exact_length_hack:
3065 /* As a safeguard don't pass any garbage to the driver. */
3066 assert (apdulen <= apdu_buffer_size);
3067 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3068 resultlen = result_buffer_size;
3069 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3070 if (rc || resultlen < 2)
3072 log_info ("apdu_send_simple(%d) failed: %s\n",
3073 slot, apdu_strerror (rc));
3074 unlock_slot (slot);
3075 xfree (apdu_buffer);
3076 xfree (result_buffer);
3077 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3079 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3080 if (!use_extended_length
3081 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3083 apdu[apdulen-1] = (sw & 0x00ff);
3084 did_exact_length_hack = 1;
3085 goto exact_length_hack;
3088 while (use_chaining && sw == SW_SUCCESS);
3090 if (apdu_buffer)
3092 xfree (apdu_buffer);
3093 apdu_buffer = NULL;
3094 apdu_buffer_size = 0;
3097 /* Store away the returned data but strip the statusword. */
3098 resultlen -= 2;
3099 if (DBG_CARD_IO)
3101 log_debug (" response: sw=%04X datalen=%d\n",
3102 sw, (unsigned int)resultlen);
3103 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3104 log_printhex (" dump: ", result, resultlen);
3107 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3109 if (retbuf)
3111 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3112 if (!*retbuf)
3114 unlock_slot (slot);
3115 xfree (result_buffer);
3116 return SW_HOST_OUT_OF_CORE;
3118 *retbuflen = resultlen;
3119 memcpy (*retbuf, result, resultlen);
3122 else if ((sw & 0xff00) == SW_MORE_DATA)
3124 unsigned char *p = NULL, *tmp;
3125 size_t bufsize = 4096;
3127 /* It is likely that we need to return much more data, so we
3128 start off with a large buffer. */
3129 if (retbuf)
3131 *retbuf = p = xtrymalloc (bufsize);
3132 if (!*retbuf)
3134 unlock_slot (slot);
3135 xfree (result_buffer);
3136 return SW_HOST_OUT_OF_CORE;
3138 assert (resultlen < bufsize);
3139 memcpy (p, result, resultlen);
3140 p += resultlen;
3145 int len = (sw & 0x00ff);
3147 if (DBG_CARD_IO)
3148 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3149 slot, len);
3150 apdu_buffer_size = sizeof short_apdu_buffer;
3151 apdu = short_apdu_buffer;
3152 apdulen = 0;
3153 apdu[apdulen++] = class;
3154 apdu[apdulen++] = 0xC0;
3155 apdu[apdulen++] = 0;
3156 apdu[apdulen++] = 0;
3157 apdu[apdulen++] = len;
3158 assert (apdulen <= apdu_buffer_size);
3159 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3160 resultlen = result_buffer_size;
3161 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3162 if (rc || resultlen < 2)
3164 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3165 slot, apdu_strerror (rc));
3166 unlock_slot (slot);
3167 xfree (result_buffer);
3168 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3170 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3171 resultlen -= 2;
3172 if (DBG_CARD_IO)
3174 log_debug (" more: sw=%04X datalen=%d\n",
3175 sw, (unsigned int)resultlen);
3176 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3177 log_printhex (" dump: ", result, resultlen);
3180 if ((sw & 0xff00) == SW_MORE_DATA
3181 || sw == SW_SUCCESS
3182 || sw == SW_EOF_REACHED )
3184 if (retbuf && resultlen)
3186 if (p - *retbuf + resultlen > bufsize)
3188 bufsize += resultlen > 4096? resultlen: 4096;
3189 tmp = xtryrealloc (*retbuf, bufsize);
3190 if (!tmp)
3192 unlock_slot (slot);
3193 xfree (result_buffer);
3194 return SW_HOST_OUT_OF_CORE;
3196 p = tmp + (p - *retbuf);
3197 *retbuf = tmp;
3199 memcpy (p, result, resultlen);
3200 p += resultlen;
3203 else
3204 log_info ("apdu_send_simple(%d) "
3205 "got unexpected status %04X from get response\n",
3206 slot, sw);
3208 while ((sw & 0xff00) == SW_MORE_DATA);
3210 if (retbuf)
3212 *retbuflen = p - *retbuf;
3213 tmp = xtryrealloc (*retbuf, *retbuflen);
3214 if (tmp)
3215 *retbuf = tmp;
3219 unlock_slot (slot);
3220 xfree (result_buffer);
3222 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3223 log_printhex (" dump: ", *retbuf, *retbuflen);
3225 return sw;
3228 /* Send an APDU to the card in SLOT. The APDU is created from all
3229 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
3230 for LC won't sent this field and the data field; in this case DATA
3231 must also be passed as NULL. If EXTENDED_MODE is not 0 command
3232 chaining or extended length will be used; see send_le for details.
3233 The return value is the status word or -1 for an invalid SLOT or
3234 other non card related error. If RETBUF is not NULL, it will
3235 receive an allocated buffer with the returned data. The length of
3236 that data will be put into *RETBUFLEN. The caller is reponsible
3237 for releasing the buffer even in case of errors. */
3239 apdu_send_le(int slot, int extended_mode,
3240 int class, int ins, int p0, int p1,
3241 int lc, const char *data, int le,
3242 unsigned char **retbuf, size_t *retbuflen)
3244 return send_le (slot, class, ins, p0, p1,
3245 lc, data, le,
3246 retbuf, retbuflen,
3247 NULL, extended_mode);
3251 /* Send an APDU to the card in SLOT. The APDU is created from all
3252 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3253 LC won't sent this field and the data field; in this case DATA must
3254 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3255 or extended length will be used; see send_le for details. The
3256 return value is the status word or -1 for an invalid SLOT or other
3257 non card related error. If RETBUF is not NULL, it will receive an
3258 allocated buffer with the returned data. The length of that data
3259 will be put into *RETBUFLEN. The caller is reponsible for
3260 releasing the buffer even in case of errors. */
3262 apdu_send (int slot, int extended_mode,
3263 int class, int ins, int p0, int p1,
3264 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
3266 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3267 retbuf, retbuflen, NULL, extended_mode);
3270 /* Send an APDU to the card in SLOT. The APDU is created from all
3271 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3272 LC won't sent this field and the data field; in this case DATA must
3273 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3274 or extended length will be used; see send_le for details. The
3275 return value is the status word or -1 for an invalid SLOT or other
3276 non card related error. No data will be returned. */
3278 apdu_send_simple (int slot, int extended_mode,
3279 int class, int ins, int p0, int p1,
3280 int lc, const char *data)
3282 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3283 extended_mode);
3287 /* Same as apdu_send_simple but uses the keypad of the reader. */
3289 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
3290 int lc, const char *data,
3291 int pin_mode,
3292 int pinlen_min, int pinlen_max, int pin_padlen)
3294 struct pininfo_s pininfo;
3296 pininfo.mode = pin_mode;
3297 pininfo.minlen = pinlen_min;
3298 pininfo.maxlen = pinlen_max;
3299 pininfo.padlen = pin_padlen;
3300 return send_le (slot, class, ins, p0, p1, lc, data, -1,
3301 NULL, NULL, &pininfo, 0);
3305 /* This is a more generic version of the apdu sending routine. It
3306 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3307 and returns with an APDU including the status word. With
3308 HANDLE_MORE set to true this function will handle the MORE DATA
3309 status and return all APDUs concatenated with one status word at
3310 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
3311 with a max. result data length of EXTENDED_LENGTH bytes. The
3312 function does not return a regular status word but 0 on success.
3313 If the slot is locked, the function returns immediately with an
3314 error. */
3316 apdu_send_direct (int slot, size_t extended_length,
3317 const unsigned char *apdudata, size_t apdudatalen,
3318 int handle_more,
3319 unsigned char **retbuf, size_t *retbuflen)
3321 #define SHORT_RESULT_BUFFER_SIZE 258
3322 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3323 unsigned char *result_buffer = NULL;
3324 size_t result_buffer_size;
3325 unsigned char *result;
3326 size_t resultlen;
3327 unsigned char short_apdu_buffer[5+256+10];
3328 unsigned char *apdu_buffer = NULL;
3329 unsigned char *apdu;
3330 size_t apdulen;
3331 int sw;
3332 long rc; /* we need a long here due to PC/SC. */
3333 int class;
3335 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3336 return SW_HOST_NO_DRIVER;
3338 if (apdudatalen > 65535)
3339 return SW_HOST_INV_VALUE;
3341 if (apdudatalen > sizeof short_apdu_buffer - 5)
3343 apdu_buffer = xtrymalloc (apdudatalen + 5);
3344 if (!apdu_buffer)
3345 return SW_HOST_OUT_OF_CORE;
3346 apdu = apdu_buffer;
3348 else
3350 apdu = short_apdu_buffer;
3352 apdulen = apdudatalen;
3353 memcpy (apdu, apdudata, apdudatalen);
3354 class = apdulen? *apdu : 0;
3356 if (extended_length >= 256 && extended_length <= 65536)
3358 result_buffer_size = extended_length;
3359 result_buffer = xtrymalloc (result_buffer_size + 10);
3360 if (!result_buffer)
3362 xfree (apdu_buffer);
3363 return SW_HOST_OUT_OF_CORE;
3365 result = result_buffer;
3367 else
3369 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3370 result = short_result_buffer;
3372 #undef SHORT_RESULT_BUFFER_SIZE
3374 if ((sw = trylock_slot (slot)))
3376 xfree (apdu_buffer);
3377 xfree (result_buffer);
3378 return sw;
3381 resultlen = result_buffer_size;
3382 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3383 xfree (apdu_buffer);
3384 apdu_buffer = NULL;
3385 if (rc || resultlen < 2)
3387 log_error ("apdu_send_direct(%d) failed: %s\n",
3388 slot, apdu_strerror (rc));
3389 unlock_slot (slot);
3390 xfree (result_buffer);
3391 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3393 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3394 /* Store away the returned data but strip the statusword. */
3395 resultlen -= 2;
3396 if (DBG_CARD_IO)
3398 log_debug (" response: sw=%04X datalen=%d\n",
3399 sw, (unsigned int)resultlen);
3400 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3401 log_printhex (" dump: ", result, resultlen);
3404 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3406 unsigned char *p = NULL, *tmp;
3407 size_t bufsize = 4096;
3409 /* It is likely that we need to return much more data, so we
3410 start off with a large buffer. */
3411 if (retbuf)
3413 *retbuf = p = xtrymalloc (bufsize + 2);
3414 if (!*retbuf)
3416 unlock_slot (slot);
3417 xfree (result_buffer);
3418 return SW_HOST_OUT_OF_CORE;
3420 assert (resultlen < bufsize);
3421 memcpy (p, result, resultlen);
3422 p += resultlen;
3427 int len = (sw & 0x00ff);
3429 if (DBG_CARD_IO)
3430 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3431 slot, len);
3432 apdu = short_apdu_buffer;
3433 apdulen = 0;
3434 apdu[apdulen++] = class;
3435 apdu[apdulen++] = 0xC0;
3436 apdu[apdulen++] = 0;
3437 apdu[apdulen++] = 0;
3438 apdu[apdulen++] = len;
3439 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3440 resultlen = result_buffer_size;
3441 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3442 if (rc || resultlen < 2)
3444 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3445 slot, apdu_strerror (rc));
3446 unlock_slot (slot);
3447 xfree (result_buffer);
3448 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3450 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3451 resultlen -= 2;
3452 if (DBG_CARD_IO)
3454 log_debug (" more: sw=%04X datalen=%d\n",
3455 sw, (unsigned int)resultlen);
3456 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3457 log_printhex (" dump: ", result, resultlen);
3460 if ((sw & 0xff00) == SW_MORE_DATA
3461 || sw == SW_SUCCESS
3462 || sw == SW_EOF_REACHED )
3464 if (retbuf && resultlen)
3466 if (p - *retbuf + resultlen > bufsize)
3468 bufsize += resultlen > 4096? resultlen: 4096;
3469 tmp = xtryrealloc (*retbuf, bufsize + 2);
3470 if (!tmp)
3472 unlock_slot (slot);
3473 xfree (result_buffer);
3474 return SW_HOST_OUT_OF_CORE;
3476 p = tmp + (p - *retbuf);
3477 *retbuf = tmp;
3479 memcpy (p, result, resultlen);
3480 p += resultlen;
3483 else
3484 log_info ("apdu_send_direct(%d) "
3485 "got unexpected status %04X from get response\n",
3486 slot, sw);
3488 while ((sw & 0xff00) == SW_MORE_DATA);
3490 if (retbuf)
3492 *retbuflen = p - *retbuf;
3493 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3494 if (tmp)
3495 *retbuf = tmp;
3498 else
3500 if (retbuf)
3502 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3503 if (!*retbuf)
3505 unlock_slot (slot);
3506 xfree (result_buffer);
3507 return SW_HOST_OUT_OF_CORE;
3509 *retbuflen = resultlen;
3510 memcpy (*retbuf, result, resultlen);
3514 unlock_slot (slot);
3515 xfree (result_buffer);
3517 /* Append the status word. Note that we reserved the two extra
3518 bytes while allocating the buffer. */
3519 if (retbuf)
3521 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3522 (*retbuf)[(*retbuflen)++] = sw;
3525 if (DBG_CARD_IO && retbuf)
3526 log_printhex (" dump: ", *retbuf, *retbuflen);
3528 return 0;