2006-09-01 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / apdu.c
blobd6bbdefd52b7a9ac20c02718be58d0c33855fdfd
1 /* apdu.c - ISO 7816 APDU functions and low level I/O
2 * Copyright (C) 2003, 2004 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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
21 * $Id$
24 /* NOTE: This module is also used by other software, thus the use of
25 the macro USE_GNU_PTH is mandatory. For GnuPG this macro is
26 guaranteed to be defined true. */
28 #include <config.h>
29 #include <errno.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34 #include <signal.h>
35 #ifdef USE_GNU_PTH
36 # include <pth.h>
37 # include <unistd.h>
38 # include <fcntl.h>
39 #endif
42 /* If requested include the definitions for the remote APDU protocol
43 code. */
44 #ifdef USE_G10CODE_RAPDU
45 #include "rapdu.h"
46 #endif /*USE_G10CODE_RAPDU*/
48 #if defined(GNUPG_SCD_MAIN_HEADER)
49 #include GNUPG_SCD_MAIN_HEADER
50 #elif GNUPG_MAJOR_VERSION == 1
51 /* This is used with GnuPG version < 1.9. The code has been source
52 copied from the current GnuPG >= 1.9 and is maintained over
53 there. */
54 #include "options.h"
55 #include "errors.h"
56 #include "memory.h"
57 #include "util.h"
58 #include "i18n.h"
59 #include "cardglue.h"
60 #else /* GNUPG_MAJOR_VERSION != 1 */
61 #include "scdaemon.h"
62 #endif /* GNUPG_MAJOR_VERSION != 1 */
64 #include "apdu.h"
65 #include "dynload.h"
66 #include "ccid-driver.h"
69 /* Due to conflicting use of threading libraries we usually can't link
70 against libpcsclite. Instead we use a wrapper program. */
71 #ifdef USE_GNU_PTH
72 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
73 #define NEED_PCSC_WRAPPER 1
74 #endif
75 #endif
78 #define MAX_READER 4 /* Number of readers we support concurrently. */
81 #if defined(_WIN32) || defined(__CYGWIN__)
82 #define DLSTDCALL __stdcall
83 #else
84 #define DLSTDCALL
85 #endif
87 #ifdef _POSIX_OPEN_MAX
88 #define MAX_OPEN_FDS _POSIX_OPEN_MAX
89 #else
90 #define MAX_OPEN_FDS 20
91 #endif
93 /* Helper to pass patrameters related to keypad based operations. */
94 struct pininfo_s
96 int mode;
97 int minlen;
98 int maxlen;
99 int padlen;
102 /* A structure to collect information pertaining to one reader
103 slot. */
104 struct reader_table_s {
105 int used; /* True if slot is used. */
106 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
108 /* Function pointers intialized to the various backends. */
109 int (*close_reader)(int);
110 int (*shutdown_reader)(int);
111 int (*reset_reader)(int);
112 int (*get_status_reader)(int, unsigned int *);
113 int (*send_apdu_reader)(int,unsigned char *,size_t,
114 unsigned char *, size_t *, struct pininfo_s *);
115 int (*check_keypad)(int, int, int, int, int, int);
116 void (*dump_status_reader)(int);
118 struct {
119 ccid_driver_t handle;
120 } ccid;
121 struct {
122 unsigned long context;
123 unsigned long card;
124 unsigned long protocol;
125 #ifdef NEED_PCSC_WRAPPER
126 int req_fd;
127 int rsp_fd;
128 pid_t pid;
129 #endif /*NEED_PCSC_WRAPPER*/
130 } pcsc;
131 #ifdef USE_G10CODE_RAPDU
132 struct {
133 rapdu_t handle;
134 } rapdu;
135 #endif /*USE_G10CODE_RAPDU*/
136 char *rdrname; /* Name of the connected reader or NULL if unknown. */
137 int last_status;
138 int status;
139 int is_t0; /* True if we know that we are running T=0. */
140 unsigned char atr[33];
141 size_t atrlen; /* A zero length indicates that the ATR has
142 not yet been read; i.e. the card is not
143 ready for use. */
144 unsigned int change_counter;
145 #ifdef USE_GNU_PTH
146 int lock_initialized;
147 pth_mutex_t lock;
148 #endif
150 typedef struct reader_table_s *reader_table_t;
152 /* A global table to keep track of active readers. */
153 static struct reader_table_s reader_table[MAX_READER];
156 /* ct API function pointer. */
157 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
158 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
159 unsigned char *sad, unsigned short lc,
160 unsigned char *cmd, unsigned short *lr,
161 unsigned char *rsp);
162 static char (* DLSTDCALL CT_close) (unsigned short ctn);
164 /* PC/SC constants and function pointer. */
165 #define PCSC_SCOPE_USER 0
166 #define PCSC_SCOPE_TERMINAL 1
167 #define PCSC_SCOPE_SYSTEM 2
168 #define PCSC_SCOPE_GLOBAL 3
170 #define PCSC_PROTOCOL_T0 1
171 #define PCSC_PROTOCOL_T1 2
172 #define PCSC_PROTOCOL_RAW 4
174 #define PCSC_SHARE_EXCLUSIVE 1
175 #define PCSC_SHARE_SHARED 2
176 #define PCSC_SHARE_DIRECT 3
178 #define PCSC_LEAVE_CARD 0
179 #define PCSC_RESET_CARD 1
180 #define PCSC_UNPOWER_CARD 2
181 #define PCSC_EJECT_CARD 3
183 #define PCSC_UNKNOWN 0x0001
184 #define PCSC_ABSENT 0x0002 /* Card is absent. */
185 #define PCSC_PRESENT 0x0004 /* Card is present. */
186 #define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
187 #define PCSC_POWERED 0x0010 /* Card is powered. */
188 #define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
189 #define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
191 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
192 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
193 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
194 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
195 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
196 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
197 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
198 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
199 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
200 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
201 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
203 /* Some PC/SC error codes. */
204 #define PCSC_E_CANCELLED 0x80100002
205 #define PCSC_E_CANT_DISPOSE 0x8010000E
206 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
207 #define PCSC_E_INVALID_ATR 0x80100015
208 #define PCSC_E_INVALID_HANDLE 0x80100003
209 #define PCSC_E_INVALID_PARAMETER 0x80100004
210 #define PCSC_E_INVALID_TARGET 0x80100005
211 #define PCSC_E_INVALID_VALUE 0x80100011
212 #define PCSC_E_NO_MEMORY 0x80100006
213 #define PCSC_E_UNKNOWN_READER 0x80100009
214 #define PCSC_E_TIMEOUT 0x8010000A
215 #define PCSC_E_SHARING_VIOLATION 0x8010000B
216 #define PCSC_E_NO_SMARTCARD 0x8010000C
217 #define PCSC_E_UNKNOWN_CARD 0x8010000D
218 #define PCSC_E_PROTO_MISMATCH 0x8010000F
219 #define PCSC_E_NOT_READY 0x80100010
220 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
221 #define PCSC_E_NOT_TRANSACTED 0x80100016
222 #define PCSC_E_READER_UNAVAILABLE 0x80100017
223 #define PCSC_W_REMOVED_CARD 0x80100069
226 struct pcsc_io_request_s
228 unsigned long protocol;
229 unsigned long pci_len;
232 typedef struct pcsc_io_request_s *pcsc_io_request_t;
234 struct pcsc_readerstate_s
236 const char *reader;
237 void *user_data;
238 unsigned long current_state;
239 unsigned long event_state;
240 unsigned long atrlen;
241 unsigned char atr[33];
244 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
246 long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
247 const void *reserved1,
248 const void *reserved2,
249 unsigned long *r_context);
250 long (* DLSTDCALL pcsc_release_context) (unsigned long context);
251 long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
252 const char *groups,
253 char *readers, unsigned long*readerslen);
254 long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
255 unsigned long timeout,
256 pcsc_readerstate_t readerstates,
257 unsigned long nreaderstates);
258 long (* DLSTDCALL pcsc_connect) (unsigned long context,
259 const char *reader,
260 unsigned long share_mode,
261 unsigned long preferred_protocols,
262 unsigned long *r_card,
263 unsigned long *r_active_protocol);
264 long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
265 unsigned long share_mode,
266 unsigned long preferred_protocols,
267 unsigned long initialization,
268 unsigned long *r_active_protocol);
269 long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
270 unsigned long disposition);
271 long (* DLSTDCALL pcsc_status) (unsigned long card,
272 char *reader, unsigned long *readerlen,
273 unsigned long *r_state,
274 unsigned long *r_protocol,
275 unsigned char *atr, unsigned long *atrlen);
276 long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
277 long (* DLSTDCALL pcsc_end_transaction) (unsigned long card);
278 long (* DLSTDCALL pcsc_transmit) (unsigned long card,
279 const pcsc_io_request_t send_pci,
280 const unsigned char *send_buffer,
281 unsigned long send_len,
282 pcsc_io_request_t recv_pci,
283 unsigned char *recv_buffer,
284 unsigned long *recv_len);
285 long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
286 unsigned long timeout);
289 /* Prototypes. */
290 static int pcsc_get_status (int slot, unsigned int *status);
295 Helper
299 /* Find an unused reader slot for PORTSTR and put it into the reader
300 table. Return -1 on error or the index into the reader table. */
301 static int
302 new_reader_slot (void)
304 int i, reader = -1;
306 for (i=0; i < MAX_READER; i++)
308 if (!reader_table[i].used && reader == -1)
309 reader = i;
311 if (reader == -1)
313 log_error ("new_reader_slot: out of slots\n");
314 return -1;
316 #ifdef USE_GNU_PTH
317 if (!reader_table[reader].lock_initialized)
319 if (!pth_mutex_init (&reader_table[reader].lock))
321 log_error ("error initializing mutex: %s\n", strerror (errno));
322 return -1;
324 reader_table[reader].lock_initialized = 1;
326 #endif /*USE_GNU_PTH*/
327 reader_table[reader].close_reader = NULL;
328 reader_table[reader].shutdown_reader = NULL;
329 reader_table[reader].reset_reader = NULL;
330 reader_table[reader].get_status_reader = NULL;
331 reader_table[reader].send_apdu_reader = NULL;
332 reader_table[reader].check_keypad = NULL;
333 reader_table[reader].dump_status_reader = NULL;
335 reader_table[reader].used = 1;
336 reader_table[reader].last_status = 0;
337 reader_table[reader].is_t0 = 1;
338 #ifdef NEED_PCSC_WRAPPER
339 reader_table[reader].pcsc.req_fd = -1;
340 reader_table[reader].pcsc.rsp_fd = -1;
341 reader_table[reader].pcsc.pid = (pid_t)(-1);
342 #endif
344 return reader;
348 static void
349 dump_reader_status (int slot)
351 if (!opt.verbose)
352 return;
354 if (reader_table[slot].dump_status_reader)
355 reader_table[slot].dump_status_reader (slot);
357 if (reader_table[slot].status != -1
358 && reader_table[slot].atrlen)
360 log_info ("slot %d: ATR=", slot);
361 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
367 static const char *
368 host_sw_string (long err)
370 switch (err)
372 case 0: return "okay";
373 case SW_HOST_OUT_OF_CORE: return "out of core";
374 case SW_HOST_INV_VALUE: return "invalid value";
375 case SW_HOST_NO_DRIVER: return "no driver";
376 case SW_HOST_NOT_SUPPORTED: return "not supported";
377 case SW_HOST_LOCKING_FAILED: return "locking failed";
378 case SW_HOST_BUSY: return "busy";
379 case SW_HOST_NO_CARD: return "no card";
380 case SW_HOST_CARD_INACTIVE: return "card inactive";
381 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
382 case SW_HOST_GENERAL_ERROR: return "general error";
383 case SW_HOST_NO_READER: return "no reader";
384 case SW_HOST_ABORTED: return "aborted";
385 case SW_HOST_NO_KEYPAD: return "no keypad";
386 default: return "unknown host status error";
391 const char *
392 apdu_strerror (int rc)
394 switch (rc)
396 case SW_EOF_REACHED : return "eof reached";
397 case SW_EEPROM_FAILURE : return "eeprom failure";
398 case SW_WRONG_LENGTH : return "wrong length";
399 case SW_CHV_WRONG : return "CHV wrong";
400 case SW_CHV_BLOCKED : return "CHV blocked";
401 case SW_USE_CONDITIONS : return "use conditions not satisfied";
402 case SW_BAD_PARAMETER : return "bad parameter";
403 case SW_NOT_SUPPORTED : return "not supported";
404 case SW_FILE_NOT_FOUND : return "file not found";
405 case SW_RECORD_NOT_FOUND:return "record not found";
406 case SW_REF_NOT_FOUND : return "reference not found";
407 case SW_BAD_P0_P1 : return "bad P0 or P1";
408 case SW_INS_NOT_SUP : return "instruction not supported";
409 case SW_CLA_NOT_SUP : return "class not supported";
410 case SW_SUCCESS : return "success";
411 default:
412 if ((rc & ~0x00ff) == SW_MORE_DATA)
413 return "more data available";
414 if ( (rc & 0x10000) )
415 return host_sw_string (rc);
416 return "unknown status error";
423 ct API Interface
426 static const char *
427 ct_error_string (long err)
429 switch (err)
431 case 0: return "okay";
432 case -1: return "invalid data";
433 case -8: return "ct error";
434 case -10: return "transmission error";
435 case -11: return "memory allocation error";
436 case -128: return "HTSI error";
437 default: return "unknown CT-API error";
442 static void
443 ct_dump_reader_status (int slot)
445 log_info ("reader slot %d: %s\n", slot,
446 reader_table[slot].status == 1? "Processor ICC present" :
447 reader_table[slot].status == 0? "Memory ICC present" :
448 "ICC not present" );
452 /* Wait for the card in SLOT and activate it. Return a status word
453 error or 0 on success. */
454 static int
455 ct_activate_card (int slot)
457 int rc;
458 unsigned char dad[1], sad[1], cmd[11], buf[256];
459 unsigned short buflen;
461 /* Check whether card has been inserted. */
462 dad[0] = 1; /* Destination address: CT. */
463 sad[0] = 2; /* Source address: Host. */
465 cmd[0] = 0x20; /* Class byte. */
466 cmd[1] = 0x13; /* Request status. */
467 cmd[2] = 0x00; /* From kernel. */
468 cmd[3] = 0x80; /* Return card's DO. */
469 cmd[4] = 0x00;
471 buflen = DIM(buf);
473 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
474 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
476 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
477 slot, ct_error_string (rc));
478 return SW_HOST_CARD_IO_ERROR;
481 /* Connected, now activate the card. */
482 dad[0] = 1; /* Destination address: CT. */
483 sad[0] = 2; /* Source address: Host. */
485 cmd[0] = 0x20; /* Class byte. */
486 cmd[1] = 0x12; /* Request ICC. */
487 cmd[2] = 0x01; /* From first interface. */
488 cmd[3] = 0x01; /* Return card's ATR. */
489 cmd[4] = 0x00;
491 buflen = DIM(buf);
493 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
494 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
496 log_error ("ct_activate_card(%d): activation failed: %s\n",
497 slot, ct_error_string (rc));
498 if (!rc)
499 log_printhex (" received data:", buf, buflen);
500 return SW_HOST_CARD_IO_ERROR;
503 /* Store the type and the ATR. */
504 if (buflen - 2 > DIM (reader_table[0].atr))
506 log_error ("ct_activate_card(%d): ATR too long\n", slot);
507 return SW_HOST_CARD_IO_ERROR;
510 reader_table[slot].status = buf[buflen - 1];
511 memcpy (reader_table[slot].atr, buf, buflen - 2);
512 reader_table[slot].atrlen = buflen - 2;
513 return 0;
517 static int
518 close_ct_reader (int slot)
520 CT_close (slot);
521 reader_table[slot].used = 0;
522 return 0;
525 static int
526 reset_ct_reader (int slot)
528 /* FIXME: Check is this is sufficient do do a reset. */
529 return ct_activate_card (slot);
533 static int
534 ct_get_status (int slot, unsigned int *status)
536 *status = 1|2|4; /* FIXME */
537 return 0;
539 return SW_HOST_NOT_SUPPORTED;
542 /* Actually send the APDU of length APDULEN to SLOT and return a
543 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
544 set to BUFLEN. Returns: CT API error code. */
545 static int
546 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
547 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
549 int rc;
550 unsigned char dad[1], sad[1];
551 unsigned short ctbuflen;
553 /* If we don't have an ATR, we need to reset the reader first. */
554 if (!reader_table[slot].atrlen
555 && (rc = reset_ct_reader (slot)))
556 return rc;
558 dad[0] = 0; /* Destination address: Card. */
559 sad[0] = 2; /* Source address: Host. */
560 ctbuflen = *buflen;
561 if (DBG_CARD_IO)
562 log_printhex (" CT_data:", apdu, apdulen);
563 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
564 *buflen = ctbuflen;
566 return rc? SW_HOST_CARD_IO_ERROR: 0;
571 /* Open a reader and return an internal handle for it. PORT is a
572 non-negative value with the port number of the reader. USB readers
573 do have port numbers starting at 32769. */
574 static int
575 open_ct_reader (int port)
577 int rc, reader;
579 if (port < 0 || port > 0xffff)
581 log_error ("open_ct_reader: invalid port %d requested\n", port);
582 return -1;
584 reader = new_reader_slot ();
585 if (reader == -1)
586 return reader;
587 reader_table[reader].port = port;
589 rc = CT_init (reader, (unsigned short)port);
590 if (rc)
592 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
593 port, ct_error_string (rc));
594 reader_table[reader].used = 0;
595 return -1;
598 /* Only try to activate the card. */
599 rc = ct_activate_card (reader);
600 if (rc)
602 reader_table[reader].atrlen = 0;
603 rc = 0;
606 reader_table[reader].close_reader = close_ct_reader;
607 reader_table[reader].reset_reader = reset_ct_reader;
608 reader_table[reader].get_status_reader = ct_get_status;
609 reader_table[reader].send_apdu_reader = ct_send_apdu;
610 reader_table[reader].check_keypad = NULL;
611 reader_table[reader].dump_status_reader = ct_dump_reader_status;
613 dump_reader_status (reader);
614 return reader;
619 PC/SC Interface
622 #ifdef NEED_PCSC_WRAPPER
623 static int
624 writen (int fd, const void *buf, size_t nbytes)
626 size_t nleft = nbytes;
627 int nwritten;
629 /* log_printhex (" writen:", buf, nbytes); */
631 while (nleft > 0)
633 #ifdef USE_GNU_PTH
634 nwritten = pth_write (fd, buf, nleft);
635 #else
636 nwritten = write (fd, buf, nleft);
637 #endif
638 if (nwritten < 0 && errno == EINTR)
639 continue;
640 if (nwritten < 0)
641 return -1;
642 nleft -= nwritten;
643 buf = (const char*)buf + nwritten;
645 return 0;
648 /* Read up to BUFLEN bytes from FD and return the number of bytes
649 actually read in NREAD. Returns -1 on error or 0 on success. */
650 static int
651 readn (int fd, void *buf, size_t buflen, size_t *nread)
653 size_t nleft = buflen;
654 int n;
655 /* void *orig_buf = buf; */
657 while (nleft > 0)
659 #ifdef USE_GNU_PTH
660 n = pth_read (fd, buf, nleft);
661 #else
662 n = read (fd, buf, nleft);
663 #endif
664 if (n < 0 && errno == EINTR)
665 continue;
666 if (n < 0)
667 return -1; /* read error. */
668 if (!n)
669 break; /* EOF */
670 nleft -= n;
671 buf = (char*)buf + n;
673 if (nread)
674 *nread = buflen - nleft;
676 /* log_printhex (" readn:", orig_buf, *nread); */
678 return 0;
680 #endif /*NEED_PCSC_WRAPPER*/
682 static const char *
683 pcsc_error_string (long err)
685 const char *s;
687 if (!err)
688 return "okay";
689 if ((err & 0x80100000) != 0x80100000)
690 return "invalid PC/SC error code";
691 err &= 0xffff;
692 switch (err)
694 case 0x0002: s = "cancelled"; break;
695 case 0x000e: s = "can't dispose"; break;
696 case 0x0008: s = "insufficient buffer"; break;
697 case 0x0015: s = "invalid ATR"; break;
698 case 0x0003: s = "invalid handle"; break;
699 case 0x0004: s = "invalid parameter"; break;
700 case 0x0005: s = "invalid target"; break;
701 case 0x0011: s = "invalid value"; break;
702 case 0x0006: s = "no memory"; break;
703 case 0x0013: s = "comm error"; break;
704 case 0x0001: s = "internal error"; break;
705 case 0x0014: s = "unknown error"; break;
706 case 0x0007: s = "waited too long"; break;
707 case 0x0009: s = "unknown reader"; break;
708 case 0x000a: s = "timeout"; break;
709 case 0x000b: s = "sharing violation"; break;
710 case 0x000c: s = "no smartcard"; break;
711 case 0x000d: s = "unknown card"; break;
712 case 0x000f: s = "proto mismatch"; break;
713 case 0x0010: s = "not ready"; break;
714 case 0x0012: s = "system cancelled"; break;
715 case 0x0016: s = "not transacted"; break;
716 case 0x0017: s = "reader unavailable"; break;
717 case 0x0065: s = "unsupported card"; break;
718 case 0x0066: s = "unresponsive card"; break;
719 case 0x0067: s = "unpowered card"; break;
720 case 0x0068: s = "reset card"; break;
721 case 0x0069: s = "removed card"; break;
722 case 0x006a: s = "inserted card"; break;
723 case 0x001f: s = "unsupported feature"; break;
724 case 0x0019: s = "PCI too small"; break;
725 case 0x001a: s = "reader unsupported"; break;
726 case 0x001b: s = "duplicate reader"; break;
727 case 0x001c: s = "card unsupported"; break;
728 case 0x001d: s = "no service"; break;
729 case 0x001e: s = "service stopped"; break;
730 default: s = "unknown PC/SC error code"; break;
732 return s;
735 /* Map PC/SC error codes to our special host status words. */
736 static int
737 pcsc_error_to_sw (long ec)
739 int rc;
741 switch (ec)
743 case 0: rc = 0; break;
745 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
746 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
747 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
748 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
749 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
750 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
752 case PCSC_E_INVALID_TARGET:
753 case PCSC_E_INVALID_VALUE:
754 case PCSC_E_INVALID_HANDLE:
755 case PCSC_E_INVALID_PARAMETER:
756 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
758 default: rc = SW_HOST_GENERAL_ERROR; break;
761 return rc;
764 static void
765 dump_pcsc_reader_status (int slot)
767 log_info ("reader slot %d: active protocol:", slot);
768 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
769 log_printf (" T0");
770 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
771 log_printf (" T1");
772 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
773 log_printf (" raw");
774 log_printf ("\n");
778 /* Send an PC/SC reset command and return a status word on error or 0
779 on success. */
780 static int
781 reset_pcsc_reader (int slot)
783 #ifdef NEED_PCSC_WRAPPER
784 long err;
785 reader_table_t slotp;
786 size_t len;
787 int i, n;
788 unsigned char msgbuf[9];
789 unsigned int dummy_status;
790 int sw = SW_HOST_CARD_IO_ERROR;
792 slotp = reader_table + slot;
794 if (slotp->pcsc.req_fd == -1
795 || slotp->pcsc.rsp_fd == -1
796 || slotp->pcsc.pid == (pid_t)(-1) )
798 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
799 return sw;
802 msgbuf[0] = 0x05; /* RESET command. */
803 len = 0;
804 msgbuf[1] = (len >> 24);
805 msgbuf[2] = (len >> 16);
806 msgbuf[3] = (len >> 8);
807 msgbuf[4] = (len );
808 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
810 log_error ("error sending PC/SC RESET request: %s\n",
811 strerror (errno));
812 goto command_failed;
815 /* Read the response. */
816 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
818 log_error ("error receiving PC/SC RESET response: %s\n",
819 i? strerror (errno) : "premature EOF");
820 goto command_failed;
822 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
823 if (msgbuf[0] != 0x81 || len < 4)
825 log_error ("invalid response header from PC/SC received\n");
826 goto command_failed;
828 len -= 4; /* Already read the error code. */
829 if (len > DIM (slotp->atr))
831 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
832 (unsigned long)len);
833 sw = SW_HOST_GENERAL_ERROR;
834 goto command_failed;
836 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
837 if (err)
839 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
840 pcsc_error_string (err), err);
841 /* If the error code is no smart card, we should not considere
842 this a major error and close the wrapper. */
843 sw = pcsc_error_to_sw (err);
844 if (err == PCSC_E_NO_SMARTCARD)
845 return sw;
846 goto command_failed;
849 /* The open function may return a zero for the ATR length to
850 indicate that no card is present. */
851 n = len;
852 if (n)
854 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
856 log_error ("error receiving PC/SC RESET response: %s\n",
857 i? strerror (errno) : "premature EOF");
858 goto command_failed;
861 slotp->atrlen = len;
863 /* Read the status so that IS_T0 will be set. */
864 pcsc_get_status (slot, &dummy_status);
866 return 0;
868 command_failed:
869 close (slotp->pcsc.req_fd);
870 close (slotp->pcsc.rsp_fd);
871 slotp->pcsc.req_fd = -1;
872 slotp->pcsc.rsp_fd = -1;
873 kill (slotp->pcsc.pid, SIGTERM);
874 slotp->pcsc.pid = (pid_t)(-1);
875 slotp->used = 0;
876 return sw;
878 #else /* !NEED_PCSC_WRAPPER */
879 long err;
880 char reader[250];
881 unsigned long nreader, atrlen;
882 unsigned long card_state, card_protocol;
884 if (reader_table[slot].pcsc.card)
886 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
887 if (err)
889 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
890 pcsc_error_string (err), err);
891 return SW_HOST_CARD_IO_ERROR;
893 reader_table[slot].pcsc.card = 0;
896 err = pcsc_connect (reader_table[slot].pcsc.context,
897 reader_table[slot].rdrname,
898 PCSC_SHARE_EXCLUSIVE,
899 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
900 &reader_table[slot].pcsc.card,
901 &reader_table[slot].pcsc.protocol);
902 if (err)
904 log_error ("pcsc_connect failed: %s (0x%lx)\n",
905 pcsc_error_string (err), err);
906 reader_table[slot].pcsc.card = 0;
907 return pcsc_error_to_sw (err);
911 atrlen = 33;
912 nreader = sizeof reader - 1;
913 err = pcsc_status (reader_table[slot].pcsc.card,
914 reader, &nreader,
915 &card_state, &card_protocol,
916 reader_table[slot].atr, &atrlen);
917 if (err)
919 log_error ("pcsc_status failed: %s (0x%lx)\n",
920 pcsc_error_string (err), err);
921 reader_table[slot].atrlen = 0;
922 return pcsc_error_to_sw (err);
924 if (atrlen >= DIM (reader_table[0].atr))
925 log_bug ("ATR returned by pcsc_status is too large\n");
926 reader_table[slot].atrlen = atrlen;
927 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
929 return 0;
930 #endif /* !NEED_PCSC_WRAPPER */
934 static int
935 pcsc_get_status (int slot, unsigned int *status)
937 #ifdef NEED_PCSC_WRAPPER
938 long err;
939 reader_table_t slotp;
940 size_t len, full_len;
941 int i, n;
942 unsigned char msgbuf[9];
943 unsigned char buffer[16];
944 int sw = SW_HOST_CARD_IO_ERROR;
946 slotp = reader_table + slot;
948 if (slotp->pcsc.req_fd == -1
949 || slotp->pcsc.rsp_fd == -1
950 || slotp->pcsc.pid == (pid_t)(-1) )
952 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
953 return sw;
956 msgbuf[0] = 0x04; /* STATUS command. */
957 len = 0;
958 msgbuf[1] = (len >> 24);
959 msgbuf[2] = (len >> 16);
960 msgbuf[3] = (len >> 8);
961 msgbuf[4] = (len );
962 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
964 log_error ("error sending PC/SC STATUS request: %s\n",
965 strerror (errno));
966 goto command_failed;
969 /* Read the response. */
970 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
972 log_error ("error receiving PC/SC STATUS response: %s\n",
973 i? strerror (errno) : "premature EOF");
974 goto command_failed;
976 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
977 if (msgbuf[0] != 0x81 || len < 4)
979 log_error ("invalid response header from PC/SC received\n");
980 goto command_failed;
982 len -= 4; /* Already read the error code. */
983 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
984 if (err)
986 log_error ("pcsc_status failed: %s (0x%lx)\n",
987 pcsc_error_string (err), err);
988 /* This is a proper error code, so return immediately. */
989 return pcsc_error_to_sw (err);
992 full_len = len;
994 /* The current version returns 3 words but we allow also for old
995 versions returning only 2 words. */
996 n = 12 < len ? 12 : len;
997 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
998 || (len != 8 && len != 12))
1000 log_error ("error receiving PC/SC STATUS response: %s\n",
1001 i? strerror (errno) : "premature EOF");
1002 goto command_failed;
1005 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
1008 full_len -= len;
1009 /* Newer versions of the wrapper might send more status bytes.
1010 Read them. */
1011 while (full_len)
1013 unsigned char dummybuf[128];
1015 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1016 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1018 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1019 i? strerror (errno) : "premature EOF");
1020 goto command_failed;
1022 full_len -= n;
1025 /* We are lucky: The wrapper already returns the data in the
1026 required format. */
1027 *status = buffer[3];
1029 return 0;
1031 command_failed:
1032 close (slotp->pcsc.req_fd);
1033 close (slotp->pcsc.rsp_fd);
1034 slotp->pcsc.req_fd = -1;
1035 slotp->pcsc.rsp_fd = -1;
1036 kill (slotp->pcsc.pid, SIGTERM);
1037 slotp->pcsc.pid = (pid_t)(-1);
1038 slotp->used = 0;
1039 return sw;
1041 #else /*!NEED_PCSC_WRAPPER*/
1043 long err;
1044 struct pcsc_readerstate_s rdrstates[1];
1046 memset (rdrstates, 0, sizeof *rdrstates);
1047 rdrstates[0].reader = reader_table[slot].rdrname;
1048 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
1049 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
1051 rdrstates, 1);
1052 if (err == PCSC_E_TIMEOUT)
1053 err = 0; /* Timeout is no error error here. */
1054 if (err)
1056 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
1057 pcsc_error_string (err), err);
1058 return pcsc_error_to_sw (err);
1062 /* log_debug */
1063 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
1064 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
1065 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
1066 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
1067 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
1068 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
1069 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
1070 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
1071 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
1072 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
1073 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
1075 *status = 0;
1076 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
1077 *status |= 2;
1078 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
1079 *status |= 4;
1080 /* We indicate a useful card if it is not in use by another
1081 application. This is because we only use exclusive access
1082 mode. */
1083 if ( (*status & 6) == 6
1084 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
1085 *status |= 1;
1087 return 0;
1088 #endif /*!NEED_PCSC_WRAPPER*/
1092 /* Actually send the APDU of length APDULEN to SLOT and return a
1093 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1094 set to BUFLEN. Returns: CT API error code. */
1095 static int
1096 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1097 unsigned char *buffer, size_t *buflen,
1098 struct pininfo_s *pininfo)
1100 #ifdef NEED_PCSC_WRAPPER
1101 long err;
1102 reader_table_t slotp;
1103 size_t len, full_len;
1104 int i, n;
1105 unsigned char msgbuf[9];
1106 int sw = SW_HOST_CARD_IO_ERROR;
1108 if (!reader_table[slot].atrlen
1109 && (err = reset_pcsc_reader (slot)))
1110 return err;
1112 if (DBG_CARD_IO)
1113 log_printhex (" PCSC_data:", apdu, apdulen);
1115 slotp = reader_table + slot;
1117 if (slotp->pcsc.req_fd == -1
1118 || slotp->pcsc.rsp_fd == -1
1119 || slotp->pcsc.pid == (pid_t)(-1) )
1121 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1122 return sw;
1125 msgbuf[0] = 0x03; /* TRANSMIT command. */
1126 len = apdulen;
1127 msgbuf[1] = (len >> 24);
1128 msgbuf[2] = (len >> 16);
1129 msgbuf[3] = (len >> 8);
1130 msgbuf[4] = (len );
1131 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1132 || writen (slotp->pcsc.req_fd, apdu, len))
1134 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1135 strerror (errno));
1136 goto command_failed;
1139 /* Read the response. */
1140 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1142 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1143 i? strerror (errno) : "premature EOF");
1144 goto command_failed;
1146 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1147 if (msgbuf[0] != 0x81 || len < 4)
1149 log_error ("invalid response header from PC/SC received\n");
1150 goto command_failed;
1152 len -= 4; /* Already read the error code. */
1153 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1154 if (err)
1156 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1157 pcsc_error_string (err), err);
1158 return pcsc_error_to_sw (err);
1161 full_len = len;
1163 n = *buflen < len ? *buflen : len;
1164 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1166 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1167 i? strerror (errno) : "premature EOF");
1168 goto command_failed;
1170 *buflen = n;
1172 full_len -= len;
1173 if (full_len)
1175 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1176 err = SW_HOST_INV_VALUE;
1178 /* We need to read any rest of the response, to keep the
1179 protocol runnng. */
1180 while (full_len)
1182 unsigned char dummybuf[128];
1184 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1185 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1187 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1188 i? strerror (errno) : "premature EOF");
1189 goto command_failed;
1191 full_len -= n;
1194 return err;
1196 command_failed:
1197 close (slotp->pcsc.req_fd);
1198 close (slotp->pcsc.rsp_fd);
1199 slotp->pcsc.req_fd = -1;
1200 slotp->pcsc.rsp_fd = -1;
1201 kill (slotp->pcsc.pid, SIGTERM);
1202 slotp->pcsc.pid = (pid_t)(-1);
1203 slotp->used = 0;
1204 return sw;
1206 #else /*!NEED_PCSC_WRAPPER*/
1208 long err;
1209 struct pcsc_io_request_s send_pci;
1210 unsigned long recv_len;
1212 if (!reader_table[slot].atrlen
1213 && (err = reset_pcsc_reader (slot)))
1214 return err;
1216 if (DBG_CARD_IO)
1217 log_printhex (" PCSC_data:", apdu, apdulen);
1219 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1220 send_pci.protocol = PCSC_PROTOCOL_T1;
1221 else
1222 send_pci.protocol = PCSC_PROTOCOL_T0;
1223 send_pci.pci_len = sizeof send_pci;
1224 recv_len = *buflen;
1225 err = pcsc_transmit (reader_table[slot].pcsc.card,
1226 &send_pci, apdu, apdulen,
1227 NULL, buffer, &recv_len);
1228 *buflen = recv_len;
1229 if (err)
1230 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1231 pcsc_error_string (err), err);
1233 return pcsc_error_to_sw (err);
1234 #endif /*!NEED_PCSC_WRAPPER*/
1238 static int
1239 close_pcsc_reader (int slot)
1241 #ifdef NEED_PCSC_WRAPPER
1242 long err;
1243 reader_table_t slotp;
1244 size_t len;
1245 int i;
1246 unsigned char msgbuf[9];
1248 slotp = reader_table + slot;
1250 if (slotp->pcsc.req_fd == -1
1251 || slotp->pcsc.rsp_fd == -1
1252 || slotp->pcsc.pid == (pid_t)(-1) )
1254 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1255 return 0;
1258 msgbuf[0] = 0x02; /* CLOSE command. */
1259 len = 0;
1260 msgbuf[1] = (len >> 24);
1261 msgbuf[2] = (len >> 16);
1262 msgbuf[3] = (len >> 8);
1263 msgbuf[4] = (len );
1264 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1266 log_error ("error sending PC/SC CLOSE request: %s\n",
1267 strerror (errno));
1268 goto command_failed;
1271 /* Read the response. */
1272 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1274 log_error ("error receiving PC/SC CLOSE response: %s\n",
1275 i? strerror (errno) : "premature EOF");
1276 goto command_failed;
1278 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1279 if (msgbuf[0] != 0x81 || len < 4)
1281 log_error ("invalid response header from PC/SC received\n");
1282 goto command_failed;
1284 len -= 4; /* Already read the error code. */
1285 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1286 if (err)
1287 log_error ("pcsc_close failed: %s (0x%lx)\n",
1288 pcsc_error_string (err), err);
1290 /* We will close the wrapper in any case - errors are merely
1291 informational. */
1293 command_failed:
1294 close (slotp->pcsc.req_fd);
1295 close (slotp->pcsc.rsp_fd);
1296 slotp->pcsc.req_fd = -1;
1297 slotp->pcsc.rsp_fd = -1;
1298 kill (slotp->pcsc.pid, SIGTERM);
1299 slotp->pcsc.pid = (pid_t)(-1);
1300 slotp->used = 0;
1301 return 0;
1303 #else /*!NEED_PCSC_WRAPPER*/
1305 pcsc_release_context (reader_table[slot].pcsc.context);
1306 xfree (reader_table[slot].rdrname);
1307 reader_table[slot].rdrname = NULL;
1308 reader_table[slot].used = 0;
1309 return 0;
1310 #endif /*!NEED_PCSC_WRAPPER*/
1313 /* Note: It is a pitty that we can't return proper error codes. */
1314 static int
1315 open_pcsc_reader (const char *portstr)
1317 #ifdef NEED_PCSC_WRAPPER
1318 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1319 needed to cope with different thread models and other peculiarities
1320 of libpcsclite. */
1321 int slot;
1322 reader_table_t slotp;
1323 int fd, rp[2], wp[2];
1324 int n, i;
1325 pid_t pid;
1326 size_t len;
1327 unsigned char msgbuf[9];
1328 int err;
1329 unsigned int dummy_status;
1330 int sw = SW_HOST_CARD_IO_ERROR;
1331 const char *wrapperpgm = GNUPG_LIBDIR "/pcsc-wrapper";
1333 if (access (wrapperpgm, X_OK))
1335 log_error ("can't run PC/SC access module `%s': %s\n",
1336 wrapperpgm, strerror (errno));
1337 return -1;
1340 slot = new_reader_slot ();
1341 if (slot == -1)
1342 return -1;
1343 slotp = reader_table + slot;
1345 /* Fire up the pcsc wrapper. We don't use any fork/exec code from
1346 the common directy but implement it direclty so that this file
1347 may still be source copied. */
1349 if (pipe (rp) == -1)
1351 log_error ("error creating a pipe: %s\n", strerror (errno));
1352 slotp->used = 0;
1353 return -1;
1355 if (pipe (wp) == -1)
1357 log_error ("error creating a pipe: %s\n", strerror (errno));
1358 close (rp[0]);
1359 close (rp[1]);
1360 slotp->used = 0;
1361 return -1;
1364 pid = fork ();
1365 if (pid == -1)
1367 log_error ("error forking process: %s\n", strerror (errno));
1368 close (rp[0]);
1369 close (rp[1]);
1370 close (wp[0]);
1371 close (wp[1]);
1372 slotp->used = 0;
1373 return -1;
1375 slotp->pcsc.pid = pid;
1377 if (!pid)
1378 { /*
1379 === Child ===
1382 /* Double fork. */
1383 pid = fork ();
1384 if (pid == -1)
1385 _exit (31);
1386 if (pid)
1387 _exit (0); /* Immediate exit this parent, so that the child
1388 gets cleaned up by the init process. */
1390 /* Connect our pipes. */
1391 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1392 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1393 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1394 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1396 /* Send stderr to the bit bucket. */
1397 fd = open ("/dev/null", O_WRONLY);
1398 if (fd == -1)
1399 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1400 if (fd != 2 && dup2 (fd, 2) == -1)
1401 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1403 /* Close all other files. */
1404 n = sysconf (_SC_OPEN_MAX);
1405 if (n < 0)
1406 n = MAX_OPEN_FDS;
1407 for (i=3; i < n; i++)
1408 close(i);
1409 errno = 0;
1411 execl (wrapperpgm,
1412 "pcsc-wrapper",
1413 "--",
1414 "1", /* API version */
1415 opt.pcsc_driver, /* Name of the PC/SC library. */
1416 NULL);
1417 _exit (31);
1421 === Parent ===
1423 close (wp[0]);
1424 close (rp[1]);
1425 slotp->pcsc.req_fd = wp[1];
1426 slotp->pcsc.rsp_fd = rp[0];
1428 /* Wait for the intermediate child to terminate. */
1429 #ifdef USE_GNU_PTH
1430 #define WAIT pth_waitpid
1431 #else
1432 #define WAIT waitpid
1433 #endif
1434 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1436 #undef X
1438 /* Now send the open request. */
1439 msgbuf[0] = 0x01; /* OPEN command. */
1440 len = portstr? strlen (portstr):0;
1441 msgbuf[1] = (len >> 24);
1442 msgbuf[2] = (len >> 16);
1443 msgbuf[3] = (len >> 8);
1444 msgbuf[4] = (len );
1445 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1446 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1448 log_error ("error sending PC/SC OPEN request: %s\n",
1449 strerror (errno));
1450 goto command_failed;
1452 /* Read the response. */
1453 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1455 log_error ("error receiving PC/SC OPEN response: %s\n",
1456 i? strerror (errno) : "premature EOF");
1457 goto command_failed;
1459 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1460 if (msgbuf[0] != 0x81 || len < 4)
1462 log_error ("invalid response header from PC/SC received\n");
1463 goto command_failed;
1465 len -= 4; /* Already read the error code. */
1466 if (len > DIM (slotp->atr))
1468 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1469 (unsigned long)len);
1470 goto command_failed;
1472 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1473 if (err)
1475 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1476 sw = pcsc_error_to_sw (err);
1477 goto command_failed;
1480 slotp->last_status = 0;
1482 /* The open request may return a zero for the ATR length to
1483 indicate that no card is present. */
1484 n = len;
1485 if (n)
1487 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1489 log_error ("error receiving PC/SC OPEN response: %s\n",
1490 i? strerror (errno) : "premature EOF");
1491 goto command_failed;
1493 /* If we got to here we know that a card is present
1494 and usable. Thus remember this. */
1495 slotp->last_status = (1|2|4| 0x8000);
1497 slotp->atrlen = len;
1499 reader_table[slot].close_reader = close_pcsc_reader;
1500 reader_table[slot].reset_reader = reset_pcsc_reader;
1501 reader_table[slot].get_status_reader = pcsc_get_status;
1502 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1503 reader_table[slot].check_keypad = NULL;
1504 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1506 /* Read the status so that IS_T0 will be set. */
1507 pcsc_get_status (slot, &dummy_status);
1509 dump_reader_status (slot);
1510 return slot;
1512 command_failed:
1513 close (slotp->pcsc.req_fd);
1514 close (slotp->pcsc.rsp_fd);
1515 slotp->pcsc.req_fd = -1;
1516 slotp->pcsc.rsp_fd = -1;
1517 kill (slotp->pcsc.pid, SIGTERM);
1518 slotp->pcsc.pid = (pid_t)(-1);
1519 slotp->used = 0;
1520 /* There is no way to return SW. */
1521 return -1;
1523 #else /*!NEED_PCSC_WRAPPER */
1524 long err;
1525 int slot;
1526 char *list = NULL;
1527 unsigned long nreader, listlen, atrlen;
1528 char *p;
1529 unsigned long card_state, card_protocol;
1531 slot = new_reader_slot ();
1532 if (slot == -1)
1533 return -1;
1535 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1536 &reader_table[slot].pcsc.context);
1537 if (err)
1539 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1540 pcsc_error_string (err), err);
1541 reader_table[slot].used = 0;
1542 return -1;
1545 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1546 NULL, NULL, &nreader);
1547 if (!err)
1549 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1550 if (!list)
1552 log_error ("error allocating memory for reader list\n");
1553 pcsc_release_context (reader_table[slot].pcsc.context);
1554 reader_table[slot].used = 0;
1555 return -1 /*SW_HOST_OUT_OF_CORE*/;
1557 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1558 NULL, list, &nreader);
1560 if (err)
1562 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1563 pcsc_error_string (err), err);
1564 pcsc_release_context (reader_table[slot].pcsc.context);
1565 reader_table[slot].used = 0;
1566 xfree (list);
1567 return -1 /*pcsc_error_to_sw (err)*/;
1570 listlen = nreader;
1571 p = list;
1572 while (nreader)
1574 if (!*p && !p[1])
1575 break;
1576 if (*p)
1577 log_info ("detected reader `%s'\n", p);
1578 if (nreader < (strlen (p)+1))
1580 log_error ("invalid response from pcsc_list_readers\n");
1581 break;
1583 nreader -= strlen (p)+1;
1584 p += strlen (p) + 1;
1587 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1588 if (!reader_table[slot].rdrname)
1590 log_error ("error allocating memory for reader name\n");
1591 pcsc_release_context (reader_table[slot].pcsc.context);
1592 reader_table[slot].used = 0;
1593 return -1 /*SW_HOST_OUT_OF_CORE*/;
1595 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1596 xfree (list);
1597 list = NULL;
1599 err = pcsc_connect (reader_table[slot].pcsc.context,
1600 reader_table[slot].rdrname,
1601 PCSC_SHARE_EXCLUSIVE,
1602 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1603 &reader_table[slot].pcsc.card,
1604 &reader_table[slot].pcsc.protocol);
1605 if (err == PCSC_E_NO_SMARTCARD)
1606 reader_table[slot].pcsc.card = 0;
1607 else if (err)
1609 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1610 pcsc_error_string (err), err);
1611 pcsc_release_context (reader_table[slot].pcsc.context);
1612 xfree (reader_table[slot].rdrname);
1613 reader_table[slot].rdrname = NULL;
1614 reader_table[slot].used = 0;
1615 return -1 /*pcsc_error_to_sw (err)*/;
1618 reader_table[slot].atrlen = 0;
1619 reader_table[slot].last_status = 0;
1620 if (!err)
1622 char reader[250];
1623 unsigned long readerlen;
1625 atrlen = 32;
1626 readerlen = sizeof reader -1 ;
1627 err = pcsc_status (reader_table[slot].pcsc.card,
1628 reader, &readerlen,
1629 &card_state, &card_protocol,
1630 reader_table[slot].atr, &atrlen);
1631 if (err)
1632 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1633 pcsc_error_string (err), err, readerlen);
1634 else
1636 if (atrlen >= DIM (reader_table[0].atr))
1637 log_bug ("ATR returned by pcsc_status is too large\n");
1638 reader_table[slot].atrlen = atrlen;
1639 /* If we got to here we know that a card is present
1640 and usable. Thus remember this. */
1641 reader_table[slot].last_status = (1|2|4| 0x8000);
1642 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1646 reader_table[slot].close_reader = close_pcsc_reader;
1647 reader_table[slot].reset_reader = reset_pcsc_reader;
1648 reader_table[slot].get_status_reader = pcsc_get_status;
1649 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1650 reader_table[slot].check_keypad = NULL;
1651 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1653 /* log_debug ("state from pcsc_status: 0x%lx\n", card_state); */
1654 /* log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
1656 dump_reader_status (slot);
1657 return slot;
1658 #endif /*!NEED_PCSC_WRAPPER */
1664 #ifdef HAVE_LIBUSB
1666 Internal CCID driver interface.
1670 static void
1671 dump_ccid_reader_status (int slot)
1673 log_info ("reader slot %d: using ccid driver\n", slot);
1676 static int
1677 close_ccid_reader (int slot)
1679 ccid_close_reader (reader_table[slot].ccid.handle);
1680 reader_table[slot].used = 0;
1681 return 0;
1685 static int
1686 shutdown_ccid_reader (int slot)
1688 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1689 return 0;
1693 static int
1694 reset_ccid_reader (int slot)
1696 int err;
1697 reader_table_t slotp = reader_table + slot;
1698 unsigned char atr[33];
1699 size_t atrlen;
1701 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1702 if (err)
1703 return err;
1704 /* If the reset was successful, update the ATR. */
1705 assert (sizeof slotp->atr >= sizeof atr);
1706 slotp->atrlen = atrlen;
1707 memcpy (slotp->atr, atr, atrlen);
1708 dump_reader_status (slot);
1709 return 0;
1713 static int
1714 get_status_ccid (int slot, unsigned int *status)
1716 int rc;
1717 int bits;
1719 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1720 if (rc)
1721 return -1;
1723 if (bits == 0)
1724 *status = 1|2|4;
1725 else if (bits == 1)
1726 *status = 2;
1727 else
1728 *status = 0;
1730 return 0;
1734 /* Actually send the APDU of length APDULEN to SLOT and return a
1735 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1736 set to BUFLEN. Returns: Internal CCID driver error code. */
1737 static int
1738 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1739 unsigned char *buffer, size_t *buflen,
1740 struct pininfo_s *pininfo)
1742 long err;
1743 size_t maxbuflen;
1745 /* If we don't have an ATR, we need to reset the reader first. */
1746 if (!reader_table[slot].atrlen
1747 && (err = reset_ccid_reader (slot)))
1748 return err;
1750 if (DBG_CARD_IO)
1751 log_printhex (" APDU_data:", apdu, apdulen);
1753 maxbuflen = *buflen;
1754 if (pininfo)
1755 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1756 apdu, apdulen,
1757 pininfo->mode,
1758 pininfo->minlen,
1759 pininfo->maxlen,
1760 pininfo->padlen,
1761 buffer, maxbuflen, buflen);
1762 else
1763 err = ccid_transceive (reader_table[slot].ccid.handle,
1764 apdu, apdulen,
1765 buffer, maxbuflen, buflen);
1766 if (err)
1767 log_error ("ccid_transceive failed: (0x%lx)\n",
1768 err);
1770 return err;
1774 /* Check whether the CCID reader supports the ISO command code COMMAND
1775 on the keypad. Return 0 on success. For a description of the pin
1776 parameters, see ccid-driver.c */
1777 static int
1778 check_ccid_keypad (int slot, int command, int pin_mode,
1779 int pinlen_min, int pinlen_max, int pin_padlen)
1781 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1783 apdu[1] = command;
1784 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1785 apdu, sizeof apdu,
1786 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1787 NULL, 0, NULL);
1791 /* Open the reader and try to read an ATR. */
1792 static int
1793 open_ccid_reader (const char *portstr)
1795 int err;
1796 int slot;
1797 reader_table_t slotp;
1799 slot = new_reader_slot ();
1800 if (slot == -1)
1801 return -1;
1802 slotp = reader_table + slot;
1804 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1805 if (err)
1807 slotp->used = 0;
1808 return -1;
1811 err = ccid_get_atr (slotp->ccid.handle,
1812 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1813 if (err)
1815 slotp->atrlen = 0;
1816 err = 0;
1818 else
1820 /* If we got to here we know that a card is present
1821 and usable. Thus remember this. */
1822 reader_table[slot].last_status = (1|2|4| 0x8000);
1825 reader_table[slot].close_reader = close_ccid_reader;
1826 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1827 reader_table[slot].reset_reader = reset_ccid_reader;
1828 reader_table[slot].get_status_reader = get_status_ccid;
1829 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1830 reader_table[slot].check_keypad = check_ccid_keypad;
1831 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1833 dump_reader_status (slot);
1834 return slot;
1839 #endif /* HAVE_LIBUSB */
1843 #ifdef USE_G10CODE_RAPDU
1845 The Remote APDU Interface.
1847 This uses the Remote APDU protocol to contact a reader.
1849 The port number is actually an index into the list of ports as
1850 returned via the protocol.
1854 static int
1855 rapdu_status_to_sw (int status)
1857 int rc;
1859 switch (status)
1861 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1863 case RAPDU_STATUS_INVCMD:
1864 case RAPDU_STATUS_INVPROT:
1865 case RAPDU_STATUS_INVSEQ:
1866 case RAPDU_STATUS_INVCOOKIE:
1867 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1869 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1870 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1871 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1872 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1873 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1874 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1876 default: rc = SW_HOST_GENERAL_ERROR; break;
1879 return rc;
1884 static int
1885 close_rapdu_reader (int slot)
1887 rapdu_release (reader_table[slot].rapdu.handle);
1888 reader_table[slot].used = 0;
1889 return 0;
1893 static int
1894 reset_rapdu_reader (int slot)
1896 int err;
1897 reader_table_t slotp;
1898 rapdu_msg_t msg = NULL;
1900 slotp = reader_table + slot;
1902 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1903 if (err)
1905 log_error ("sending rapdu command RESET failed: %s\n",
1906 err < 0 ? strerror (errno): rapdu_strerror (err));
1907 rapdu_msg_release (msg);
1908 return rapdu_status_to_sw (err);
1910 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1911 if (err)
1913 log_error ("receiving rapdu message failed: %s\n",
1914 err < 0 ? strerror (errno): rapdu_strerror (err));
1915 rapdu_msg_release (msg);
1916 return rapdu_status_to_sw (err);
1918 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1920 int sw = rapdu_status_to_sw (msg->cmd);
1921 log_error ("rapdu command RESET failed: %s\n",
1922 rapdu_strerror (msg->cmd));
1923 rapdu_msg_release (msg);
1924 return sw;
1926 if (msg->datalen >= DIM (slotp->atr))
1928 log_error ("ATR returned by the RAPDU layer is too large\n");
1929 rapdu_msg_release (msg);
1930 return SW_HOST_INV_VALUE;
1932 slotp->atrlen = msg->datalen;
1933 memcpy (slotp->atr, msg->data, msg->datalen);
1935 rapdu_msg_release (msg);
1936 return 0;
1940 static int
1941 my_rapdu_get_status (int slot, unsigned int *status)
1943 int err;
1944 reader_table_t slotp;
1945 rapdu_msg_t msg = NULL;
1946 int oldslot;
1948 slotp = reader_table + slot;
1950 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
1951 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
1952 rapdu_set_reader (slotp->rapdu.handle, oldslot);
1953 if (err)
1955 log_error ("sending rapdu command GET_STATUS failed: %s\n",
1956 err < 0 ? strerror (errno): rapdu_strerror (err));
1957 return rapdu_status_to_sw (err);
1959 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1960 if (err)
1962 log_error ("receiving rapdu message failed: %s\n",
1963 err < 0 ? strerror (errno): rapdu_strerror (err));
1964 rapdu_msg_release (msg);
1965 return rapdu_status_to_sw (err);
1967 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1969 int sw = rapdu_status_to_sw (msg->cmd);
1970 log_error ("rapdu command GET_STATUS failed: %s\n",
1971 rapdu_strerror (msg->cmd));
1972 rapdu_msg_release (msg);
1973 return sw;
1975 *status = msg->data[0];
1977 rapdu_msg_release (msg);
1978 return 0;
1982 /* Actually send the APDU of length APDULEN to SLOT and return a
1983 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1984 set to BUFLEN. Returns: APDU error code. */
1985 static int
1986 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1987 unsigned char *buffer, size_t *buflen,
1988 struct pininfo_s *pininfo)
1990 int err;
1991 reader_table_t slotp;
1992 rapdu_msg_t msg = NULL;
1993 size_t maxlen = *buflen;
1995 slotp = reader_table + slot;
1997 *buflen = 0;
1998 if (DBG_CARD_IO)
1999 log_printhex (" APDU_data:", apdu, apdulen);
2001 if (apdulen < 4)
2003 log_error ("rapdu_send_apdu: APDU is too short\n");
2004 return SW_HOST_INV_VALUE;
2007 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2008 if (err)
2010 log_error ("sending rapdu command APDU failed: %s\n",
2011 err < 0 ? strerror (errno): rapdu_strerror (err));
2012 rapdu_msg_release (msg);
2013 return rapdu_status_to_sw (err);
2015 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2016 if (err)
2018 log_error ("receiving rapdu message failed: %s\n",
2019 err < 0 ? strerror (errno): rapdu_strerror (err));
2020 rapdu_msg_release (msg);
2021 return rapdu_status_to_sw (err);
2023 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2025 int sw = rapdu_status_to_sw (msg->cmd);
2026 log_error ("rapdu command APDU failed: %s\n",
2027 rapdu_strerror (msg->cmd));
2028 rapdu_msg_release (msg);
2029 return sw;
2032 if (msg->datalen > maxlen)
2034 log_error ("rapdu response apdu too large\n");
2035 rapdu_msg_release (msg);
2036 return SW_HOST_INV_VALUE;
2039 *buflen = msg->datalen;
2040 memcpy (buffer, msg->data, msg->datalen);
2042 rapdu_msg_release (msg);
2043 return 0;
2046 static int
2047 open_rapdu_reader (int portno,
2048 const unsigned char *cookie, size_t length,
2049 int (*readfnc) (void *opaque,
2050 void *buffer, size_t size),
2051 void *readfnc_value,
2052 int (*writefnc) (void *opaque,
2053 const void *buffer, size_t size),
2054 void *writefnc_value,
2055 void (*closefnc) (void *opaque),
2056 void *closefnc_value)
2058 int err;
2059 int slot;
2060 reader_table_t slotp;
2061 rapdu_msg_t msg = NULL;
2063 slot = new_reader_slot ();
2064 if (slot == -1)
2065 return -1;
2066 slotp = reader_table + slot;
2068 slotp->rapdu.handle = rapdu_new ();
2069 if (!slotp->rapdu.handle)
2071 slotp->used = 0;
2072 return -1;
2075 rapdu_set_reader (slotp->rapdu.handle, portno);
2077 rapdu_set_iofunc (slotp->rapdu.handle,
2078 readfnc, readfnc_value,
2079 writefnc, writefnc_value,
2080 closefnc, closefnc_value);
2081 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2083 /* First try to get the current ATR, but if the card is inactive
2084 issue a reset instead. */
2085 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2086 if (err == RAPDU_STATUS_NEEDRESET)
2087 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2088 if (err)
2090 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2091 err < 0 ? strerror (errno): rapdu_strerror (err));
2092 goto failure;
2094 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2095 if (err)
2097 log_info ("receiving rapdu message failed: %s\n",
2098 err < 0 ? strerror (errno): rapdu_strerror (err));
2099 goto failure;
2101 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2103 log_info ("rapdu command GET ATR failed: %s\n",
2104 rapdu_strerror (msg->cmd));
2105 goto failure;
2107 if (msg->datalen >= DIM (slotp->atr))
2109 log_error ("ATR returned by the RAPDU layer is too large\n");
2110 goto failure;
2112 slotp->atrlen = msg->datalen;
2113 memcpy (slotp->atr, msg->data, msg->datalen);
2115 reader_table[slot].close_reader = close_rapdu_reader;
2116 reader_table[slot].reset_reader = reset_rapdu_reader;
2117 reader_table[slot].get_status_reader = my_rapdu_get_status;
2118 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2119 reader_table[slot].check_keypad = NULL;
2120 reader_table[slot].dump_status_reader = NULL;
2122 dump_reader_status (slot);
2123 rapdu_msg_release (msg);
2124 return slot;
2126 failure:
2127 rapdu_msg_release (msg);
2128 rapdu_release (slotp->rapdu.handle);
2129 slotp->used = 0;
2130 return -1;
2133 #endif /*USE_G10CODE_RAPDU*/
2138 Driver Access
2142 static int
2143 lock_slot (int slot)
2145 #ifdef USE_GNU_PTH
2146 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2148 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2149 return SW_HOST_LOCKING_FAILED;
2151 #endif /*USE_GNU_PTH*/
2152 return 0;
2155 static int
2156 trylock_slot (int slot)
2158 #ifdef USE_GNU_PTH
2159 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2161 if (errno == EBUSY)
2162 return SW_HOST_BUSY;
2163 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2164 return SW_HOST_LOCKING_FAILED;
2166 #endif /*USE_GNU_PTH*/
2167 return 0;
2170 static void
2171 unlock_slot (int slot)
2173 #ifdef USE_GNU_PTH
2174 if (!pth_mutex_release (&reader_table[slot].lock))
2175 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2176 #endif /*USE_GNU_PTH*/
2180 /* Open the reader and return an internal slot number or -1 on
2181 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2182 the first USB reader. For PC/SC the first listed reader). */
2184 apdu_open_reader (const char *portstr)
2186 static int pcsc_api_loaded, ct_api_loaded;
2188 #ifdef HAVE_LIBUSB
2189 if (!opt.disable_ccid)
2191 int slot, i;
2192 const char *s;
2194 slot = open_ccid_reader (portstr);
2195 if (slot != -1)
2196 return slot; /* got one */
2198 /* If a CCID reader specification has been given, the user does
2199 not want a fallback to other drivers. */
2200 if (portstr)
2201 for (s=portstr, i=0; *s; s++)
2202 if (*s == ':' && (++i == 3))
2203 return -1;
2206 #endif /* HAVE_LIBUSB */
2208 if (opt.ctapi_driver && *opt.ctapi_driver)
2210 int port = portstr? atoi (portstr) : 32768;
2212 if (!ct_api_loaded)
2214 void *handle;
2216 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2217 if (!handle)
2219 log_error ("apdu_open_reader: failed to open driver: %s\n",
2220 dlerror ());
2221 return -1;
2223 CT_init = dlsym (handle, "CT_init");
2224 CT_data = dlsym (handle, "CT_data");
2225 CT_close = dlsym (handle, "CT_close");
2226 if (!CT_init || !CT_data || !CT_close)
2228 log_error ("apdu_open_reader: invalid CT-API driver\n");
2229 dlclose (handle);
2230 return -1;
2232 ct_api_loaded = 1;
2234 return open_ct_reader (port);
2238 /* No ctAPI configured, so lets try the PC/SC API */
2239 if (!pcsc_api_loaded)
2241 #ifndef NEED_PCSC_WRAPPER
2242 void *handle;
2244 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2245 if (!handle)
2247 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2248 opt.pcsc_driver, dlerror ());
2249 return -1;
2252 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2253 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2254 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2255 #if defined(_WIN32) || defined(__CYGWIN__)
2256 if (!pcsc_list_readers)
2257 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2258 #endif
2259 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2260 #if defined(_WIN32) || defined(__CYGWIN__)
2261 if (!pcsc_get_status_change)
2262 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2263 #endif
2264 pcsc_connect = dlsym (handle, "SCardConnect");
2265 #if defined(_WIN32) || defined(__CYGWIN__)
2266 if (!pcsc_connect)
2267 pcsc_connect = dlsym (handle, "SCardConnectA");
2268 #endif
2269 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2270 #if defined(_WIN32) || defined(__CYGWIN__)
2271 if (!pcsc_reconnect)
2272 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2273 #endif
2274 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2275 pcsc_status = dlsym (handle, "SCardStatus");
2276 #if defined(_WIN32) || defined(__CYGWIN__)
2277 if (!pcsc_status)
2278 pcsc_status = dlsym (handle, "SCardStatusA");
2279 #endif
2280 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2281 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2282 pcsc_transmit = dlsym (handle, "SCardTransmit");
2283 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2285 if (!pcsc_establish_context
2286 || !pcsc_release_context
2287 || !pcsc_list_readers
2288 || !pcsc_get_status_change
2289 || !pcsc_connect
2290 || !pcsc_reconnect
2291 || !pcsc_disconnect
2292 || !pcsc_status
2293 || !pcsc_begin_transaction
2294 || !pcsc_end_transaction
2295 || !pcsc_transmit
2296 /* || !pcsc_set_timeout */)
2298 /* Note that set_timeout is currently not used and also not
2299 available under Windows. */
2300 log_error ("apdu_open_reader: invalid PC/SC driver "
2301 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2302 !!pcsc_establish_context,
2303 !!pcsc_release_context,
2304 !!pcsc_list_readers,
2305 !!pcsc_get_status_change,
2306 !!pcsc_connect,
2307 !!pcsc_reconnect,
2308 !!pcsc_disconnect,
2309 !!pcsc_status,
2310 !!pcsc_begin_transaction,
2311 !!pcsc_end_transaction,
2312 !!pcsc_transmit,
2313 !!pcsc_set_timeout );
2314 dlclose (handle);
2315 return -1;
2317 #endif /*!NEED_PCSC_WRAPPER*/
2318 pcsc_api_loaded = 1;
2321 return open_pcsc_reader (portstr);
2325 /* Open an remote reader and return an internal slot number or -1 on
2326 error. This function is an alternative to apdu_open_reader and used
2327 with remote readers only. Note that the supplied CLOSEFNC will
2328 only be called once and the slot will not be valid afther this.
2330 If PORTSTR is NULL we default to the first availabe port.
2333 apdu_open_remote_reader (const char *portstr,
2334 const unsigned char *cookie, size_t length,
2335 int (*readfnc) (void *opaque,
2336 void *buffer, size_t size),
2337 void *readfnc_value,
2338 int (*writefnc) (void *opaque,
2339 const void *buffer, size_t size),
2340 void *writefnc_value,
2341 void (*closefnc) (void *opaque),
2342 void *closefnc_value)
2344 #ifdef USE_G10CODE_RAPDU
2345 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2346 cookie, length,
2347 readfnc, readfnc_value,
2348 writefnc, writefnc_value,
2349 closefnc, closefnc_value);
2350 #else
2351 #ifdef _WIN32
2352 errno = ENOENT;
2353 #else
2354 errno = ENOSYS;
2355 #endif
2356 return -1;
2357 #endif
2362 apdu_close_reader (int slot)
2364 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2365 return SW_HOST_NO_DRIVER;
2366 if (reader_table[slot].close_reader)
2367 return reader_table[slot].close_reader (slot);
2368 return SW_HOST_NOT_SUPPORTED;
2371 /* Shutdown a reader; that is basically the same as a close but keeps
2372 the handle ready for later use. A apdu_reset_reader should be used
2373 to get it active again. */
2375 apdu_shutdown_reader (int slot)
2377 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2378 return SW_HOST_NO_DRIVER;
2379 if (reader_table[slot].shutdown_reader)
2380 return reader_table[slot].shutdown_reader (slot);
2381 return SW_HOST_NOT_SUPPORTED;
2384 /* Enumerate all readers and return information on whether this reader
2385 is in use. The caller should start with SLOT set to 0 and
2386 increment it with each call until an error is returned. */
2388 apdu_enum_reader (int slot, int *used)
2390 if (slot < 0 || slot >= MAX_READER)
2391 return SW_HOST_NO_DRIVER;
2392 *used = reader_table[slot].used;
2393 return 0;
2396 /* Do a reset for the card in reader at SLOT. */
2398 apdu_reset (int slot)
2400 int sw;
2402 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2403 return SW_HOST_NO_DRIVER;
2405 if ((sw = lock_slot (slot)))
2406 return sw;
2408 reader_table[slot].last_status = 0;
2409 if (reader_table[slot].reset_reader)
2410 sw = reader_table[slot].reset_reader (slot);
2412 if (!sw)
2414 /* If we got to here we know that a card is present
2415 and usable. Thus remember this. */
2416 reader_table[slot].last_status = (1|2|4| 0x8000);
2419 unlock_slot (slot);
2420 return sw;
2424 /* Activate a card if it has not yet been done. This is a kind of
2425 reset-if-required. It is useful to test for presence of a card
2426 before issuing a bunch of apdu commands. It does not wait on a
2427 locked card. */
2429 apdu_activate (int slot)
2431 int sw;
2432 unsigned int s;
2434 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2435 return SW_HOST_NO_DRIVER;
2437 if ((sw = trylock_slot (slot)))
2438 return sw;
2440 if (reader_table[slot].get_status_reader)
2441 sw = reader_table[slot].get_status_reader (slot, &s);
2443 if (!sw)
2445 if (!(s & 2)) /* Card not present. */
2446 sw = SW_HOST_NO_CARD;
2447 else if ( ((s & 2) && !(s & 4))
2448 || !reader_table[slot].atrlen )
2450 /* We don't have an ATR or a card is present though inactive:
2451 do a reset now. */
2452 if (reader_table[slot].reset_reader)
2454 reader_table[slot].last_status = 0;
2455 sw = reader_table[slot].reset_reader (slot);
2456 if (!sw)
2458 /* If we got to here we know that a card is present
2459 and usable. Thus remember this. */
2460 reader_table[slot].last_status = (1|2|4| 0x8000);
2466 unlock_slot (slot);
2467 return sw;
2472 unsigned char *
2473 apdu_get_atr (int slot, size_t *atrlen)
2475 unsigned char *buf;
2477 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2478 return NULL;
2480 buf = xtrymalloc (reader_table[slot].atrlen);
2481 if (!buf)
2482 return NULL;
2483 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2484 *atrlen = reader_table[slot].atrlen;
2485 return buf;
2490 /* Retrieve the status for SLOT. The function does only wait for the
2491 card to become available if HANG is set to true. On success the
2492 bits in STATUS will be set to
2494 bit 0 = card present and usable
2495 bit 1 = card present
2496 bit 2 = card active
2497 bit 3 = card access locked [not yet implemented]
2499 For must application, testing bit 0 is sufficient.
2501 CHANGED will receive the value of the counter tracking the number
2502 of card insertions. This value may be used to detect a card
2503 change.
2506 apdu_get_status (int slot, int hang,
2507 unsigned int *status, unsigned int *changed)
2509 int sw;
2510 unsigned int s;
2512 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2513 return SW_HOST_NO_DRIVER;
2515 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2516 return sw;
2518 if (reader_table[slot].get_status_reader)
2519 sw = reader_table[slot].get_status_reader (slot, &s);
2521 unlock_slot (slot);
2523 if (sw)
2525 reader_table[slot].last_status = 0;
2526 return sw;
2529 /* Keep track of changes. We use one extra bit to test whether we
2530 have checked the status at least once. */
2531 if ( s != (reader_table[slot].last_status & 0x07ff)
2532 || !reader_table[slot].last_status )
2534 reader_table[slot].change_counter++;
2535 /* Make sure that the ATR is invalid so that a reset will be by
2536 activate. */
2537 reader_table[slot].atrlen = 0;
2539 reader_table[slot].last_status = (s | 0x8000);
2541 if (status)
2542 *status = s;
2543 if (changed)
2544 *changed = reader_table[slot].change_counter;
2545 return 0;
2549 /* Check whether the reader supports the ISO command code COMMAND on
2550 the keypad. Return 0 on success. For a description of the pin
2551 parameters, see ccid-driver.c */
2553 apdu_check_keypad (int slot, int command, int pin_mode,
2554 int pinlen_min, int pinlen_max, int pin_padlen)
2556 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2557 return SW_HOST_NO_DRIVER;
2559 if (reader_table[slot].check_keypad)
2560 return reader_table[slot].check_keypad (slot, command,
2561 pin_mode, pinlen_min, pinlen_max,
2562 pin_padlen);
2563 else
2564 return SW_HOST_NOT_SUPPORTED;
2568 /* Dispatcher for the actual send_apdu function. Note, that this
2569 function should be called in locked state. */
2570 static int
2571 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2572 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2574 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2575 return SW_HOST_NO_DRIVER;
2577 if (reader_table[slot].send_apdu_reader)
2578 return reader_table[slot].send_apdu_reader (slot,
2579 apdu, apdulen,
2580 buffer, buflen, pininfo);
2581 else
2582 return SW_HOST_NOT_SUPPORTED;
2586 /* Core APDU trabceiver function. Parameters are described at
2587 apdu_send_le with the exception of PININFO which indicates keypad
2588 related operations if not NULL. */
2589 static int
2590 send_le (int slot, int class, int ins, int p0, int p1,
2591 int lc, const char *data, int le,
2592 unsigned char **retbuf, size_t *retbuflen,
2593 struct pininfo_s *pininfo)
2595 #define RESULTLEN 256
2596 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2597 the driver. */
2598 size_t resultlen;
2599 unsigned char apdu[5+256+1];
2600 size_t apdulen;
2601 int sw;
2602 long rc; /* we need a long here due to PC/SC. */
2604 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2605 return SW_HOST_NO_DRIVER;
2607 if (DBG_CARD_IO)
2608 log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
2609 class, ins, p0, p1, lc, le);
2611 if (lc != -1 && (lc > 255 || lc < 0))
2612 return SW_WRONG_LENGTH;
2613 if (le != -1 && (le > 256 || le < 0))
2614 return SW_WRONG_LENGTH;
2615 if ((!data && lc != -1) || (data && lc == -1))
2616 return SW_HOST_INV_VALUE;
2618 if ((sw = lock_slot (slot)))
2619 return sw;
2621 apdulen = 0;
2622 apdu[apdulen++] = class;
2623 apdu[apdulen++] = ins;
2624 apdu[apdulen++] = p0;
2625 apdu[apdulen++] = p1;
2626 if (lc != -1)
2628 apdu[apdulen++] = lc;
2629 memcpy (apdu+apdulen, data, lc);
2630 apdulen += lc;
2631 /* T=0 does not allow the use of Lc together with Le; thus
2632 disable Le in this case. */
2633 if (reader_table[slot].is_t0)
2634 le = -1;
2636 if (le != -1)
2637 apdu[apdulen++] = le; /* Truncation is okay because 0 means 256. */
2638 assert (sizeof (apdu) >= apdulen);
2639 /* As safeguard don't pass any garbage from the stack to the driver. */
2640 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2641 resultlen = RESULTLEN;
2642 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2643 if (rc || resultlen < 2)
2645 log_error ("apdu_send_simple(%d) failed: %s\n",
2646 slot, apdu_strerror (rc));
2647 unlock_slot (slot);
2648 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2650 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2651 /* store away the returned data but strip the statusword. */
2652 resultlen -= 2;
2653 if (DBG_CARD_IO)
2655 log_debug (" response: sw=%04X datalen=%d\n",
2656 sw, (unsigned int)resultlen);
2657 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2658 log_printhex (" dump: ", result, resultlen);
2661 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2663 if (retbuf)
2665 *retbuf = xtrymalloc (resultlen? resultlen : 1);
2666 if (!*retbuf)
2668 unlock_slot (slot);
2669 return SW_HOST_OUT_OF_CORE;
2671 *retbuflen = resultlen;
2672 memcpy (*retbuf, result, resultlen);
2675 else if ((sw & 0xff00) == SW_MORE_DATA)
2677 unsigned char *p = NULL, *tmp;
2678 size_t bufsize = 4096;
2680 /* It is likely that we need to return much more data, so we
2681 start off with a large buffer. */
2682 if (retbuf)
2684 *retbuf = p = xtrymalloc (bufsize);
2685 if (!*retbuf)
2687 unlock_slot (slot);
2688 return SW_HOST_OUT_OF_CORE;
2690 assert (resultlen < bufsize);
2691 memcpy (p, result, resultlen);
2692 p += resultlen;
2697 int len = (sw & 0x00ff);
2699 if (DBG_CARD_IO)
2700 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2701 slot, len);
2702 apdulen = 0;
2703 apdu[apdulen++] = class;
2704 apdu[apdulen++] = 0xC0;
2705 apdu[apdulen++] = 0;
2706 apdu[apdulen++] = 0;
2707 apdu[apdulen++] = len;
2708 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2709 resultlen = RESULTLEN;
2710 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2711 if (rc || resultlen < 2)
2713 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2714 slot, apdu_strerror (rc));
2715 unlock_slot (slot);
2716 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2718 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2719 resultlen -= 2;
2720 if (DBG_CARD_IO)
2722 log_debug (" more: sw=%04X datalen=%d\n",
2723 sw, (unsigned int)resultlen);
2724 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2725 log_printhex (" dump: ", result, resultlen);
2728 if ((sw & 0xff00) == SW_MORE_DATA
2729 || sw == SW_SUCCESS
2730 || sw == SW_EOF_REACHED )
2732 if (retbuf && resultlen)
2734 if (p - *retbuf + resultlen > bufsize)
2736 bufsize += resultlen > 4096? resultlen: 4096;
2737 tmp = xtryrealloc (*retbuf, bufsize);
2738 if (!tmp)
2740 unlock_slot (slot);
2741 return SW_HOST_OUT_OF_CORE;
2743 p = tmp + (p - *retbuf);
2744 *retbuf = tmp;
2746 memcpy (p, result, resultlen);
2747 p += resultlen;
2750 else
2751 log_info ("apdu_send_simple(%d) "
2752 "got unexpected status %04X from get response\n",
2753 slot, sw);
2755 while ((sw & 0xff00) == SW_MORE_DATA);
2757 if (retbuf)
2759 *retbuflen = p - *retbuf;
2760 tmp = xtryrealloc (*retbuf, *retbuflen);
2761 if (tmp)
2762 *retbuf = tmp;
2766 unlock_slot (slot);
2768 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2769 log_printhex (" dump: ", *retbuf, *retbuflen);
2771 return sw;
2772 #undef RESULTLEN
2775 /* Send an APDU to the card in SLOT. The APDU is created from all
2776 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2777 for LC won't sent this field and the data field; in this case DATA
2778 must also be passed as NULL. The return value is the status word
2779 or -1 for an invalid SLOT or other non card related error. If
2780 RETBUF is not NULL, it will receive an allocated buffer with the
2781 returned data. The length of that data will be put into
2782 *RETBUFLEN. The caller is reponsible for releasing the buffer even
2783 in case of errors. */
2785 apdu_send_le(int slot, int class, int ins, int p0, int p1,
2786 int lc, const char *data, int le,
2787 unsigned char **retbuf, size_t *retbuflen)
2789 return send_le (slot, class, ins, p0, p1,
2790 lc, data, le,
2791 retbuf, retbuflen,
2792 NULL);
2796 /* Send an APDU to the card in SLOT. The APDU is created from all
2797 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2798 LC won't sent this field and the data field; in this case DATA must
2799 also be passed as NULL. The return value is the status word or -1
2800 for an invalid SLOT or other non card related error. If RETBUF is
2801 not NULL, it will receive an allocated buffer with the returned
2802 data. The length of that data will be put into *RETBUFLEN. The
2803 caller is reponsible for releasing the buffer even in case of
2804 errors. */
2806 apdu_send (int slot, int class, int ins, int p0, int p1,
2807 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2809 return send_le (slot, class, ins, p0, p1, lc, data, 256,
2810 retbuf, retbuflen, NULL);
2813 /* Send an APDU to the card in SLOT. The APDU is created from all
2814 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2815 LC won't sent this field and the data field; in this case DATA must
2816 also be passed as NULL. The return value is the status word or -1
2817 for an invalid SLOT or other non card related error. No data will be
2818 returned. */
2820 apdu_send_simple (int slot, int class, int ins, int p0, int p1,
2821 int lc, const char *data)
2823 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL);
2827 /* Same as apdu_send_simple but uses the keypad of the reader. */
2829 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
2830 int lc, const char *data,
2831 int pin_mode,
2832 int pinlen_min, int pinlen_max, int pin_padlen)
2834 struct pininfo_s pininfo;
2836 pininfo.mode = pin_mode;
2837 pininfo.minlen = pinlen_min;
2838 pininfo.maxlen = pinlen_max;
2839 pininfo.padlen = pin_padlen;
2840 return send_le (slot, class, ins, p0, p1, lc, data, -1,
2841 NULL, NULL, &pininfo);
2845 /* This is a more generic version of the apdu sending routine. It
2846 takes an already formatted APDU in APDUDATA or length APDUDATALEN
2847 and returns the with the APDU including the status word. With
2848 HANDLE_MORE set to true this function will handle the MORE DATA
2849 status and return all APDUs concatenated with one status word at
2850 the end. The function does not return a regular status word but 0
2851 on success. If the slot is locked, the function returns
2852 immediately with an error. */
2854 apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
2855 int handle_more,
2856 unsigned char **retbuf, size_t *retbuflen)
2858 #define RESULTLEN 256
2859 unsigned char apdu[5+256+1];
2860 size_t apdulen;
2861 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2862 the driver. */
2863 size_t resultlen;
2864 int sw;
2865 long rc; /* we need a long here due to PC/SC. */
2866 int class;
2868 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2869 return SW_HOST_NO_DRIVER;
2871 if ((sw = trylock_slot (slot)))
2872 return sw;
2874 /* We simply trunctate a too long APDU. */
2875 if (apdudatalen > sizeof apdu)
2876 apdudatalen = sizeof apdu;
2877 apdulen = apdudatalen;
2878 memcpy (apdu, apdudata, apdudatalen);
2879 class = apdulen? *apdu : 0;
2881 resultlen = RESULTLEN;
2882 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2883 if (rc || resultlen < 2)
2885 log_error ("apdu_send_direct(%d) failed: %s\n",
2886 slot, apdu_strerror (rc));
2887 unlock_slot (slot);
2888 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2890 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2891 /* Store away the returned data but strip the statusword. */
2892 resultlen -= 2;
2893 if (DBG_CARD_IO)
2895 log_debug (" response: sw=%04X datalen=%d\n",
2896 sw, (unsigned int)resultlen);
2897 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2898 log_printhex (" dump: ", result, resultlen);
2901 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
2903 unsigned char *p = NULL, *tmp;
2904 size_t bufsize = 4096;
2906 /* It is likely that we need to return much more data, so we
2907 start off with a large buffer. */
2908 if (retbuf)
2910 *retbuf = p = xtrymalloc (bufsize + 2);
2911 if (!*retbuf)
2913 unlock_slot (slot);
2914 return SW_HOST_OUT_OF_CORE;
2916 assert (resultlen < bufsize);
2917 memcpy (p, result, resultlen);
2918 p += resultlen;
2923 int len = (sw & 0x00ff);
2925 if (DBG_CARD_IO)
2926 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
2927 slot, len);
2928 apdulen = 0;
2929 apdu[apdulen++] = class;
2930 apdu[apdulen++] = 0xC0;
2931 apdu[apdulen++] = 0;
2932 apdu[apdulen++] = 0;
2933 apdu[apdulen++] = len;
2934 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2935 resultlen = RESULTLEN;
2936 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2937 if (rc || resultlen < 2)
2939 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
2940 slot, apdu_strerror (rc));
2941 unlock_slot (slot);
2942 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2944 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2945 resultlen -= 2;
2946 if (DBG_CARD_IO)
2948 log_debug (" more: sw=%04X datalen=%d\n",
2949 sw, (unsigned int)resultlen);
2950 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2951 log_printhex (" dump: ", result, resultlen);
2954 if ((sw & 0xff00) == SW_MORE_DATA
2955 || sw == SW_SUCCESS
2956 || sw == SW_EOF_REACHED )
2958 if (retbuf && resultlen)
2960 if (p - *retbuf + resultlen > bufsize)
2962 bufsize += resultlen > 4096? resultlen: 4096;
2963 tmp = xtryrealloc (*retbuf, bufsize + 2);
2964 if (!tmp)
2966 unlock_slot (slot);
2967 return SW_HOST_OUT_OF_CORE;
2969 p = tmp + (p - *retbuf);
2970 *retbuf = tmp;
2972 memcpy (p, result, resultlen);
2973 p += resultlen;
2976 else
2977 log_info ("apdu_send_sdirect(%d) "
2978 "got unexpected status %04X from get response\n",
2979 slot, sw);
2981 while ((sw & 0xff00) == SW_MORE_DATA);
2983 if (retbuf)
2985 *retbuflen = p - *retbuf;
2986 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
2987 if (tmp)
2988 *retbuf = tmp;
2991 else
2993 if (retbuf)
2995 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
2996 if (!*retbuf)
2998 unlock_slot (slot);
2999 return SW_HOST_OUT_OF_CORE;
3001 *retbuflen = resultlen;
3002 memcpy (*retbuf, result, resultlen);
3006 unlock_slot (slot);
3008 /* Append the status word - we reseved the two extra bytes while
3009 allocating the buffer. */
3010 if (retbuf)
3012 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3013 (*retbuf)[(*retbuflen)++] = sw;
3016 if (DBG_CARD_IO && retbuf)
3017 log_printhex (" dump: ", *retbuf, *retbuflen);
3019 return 0;
3020 #undef RESULTLEN