* exec.c (make_tempdir) [_WIN32]: Modified to properly handle
[gnupg.git] / g10 / apdu.c
blob52fdbc7237dbb7b74f4973252c348a7bddc73752
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;
1332 slot = new_reader_slot ();
1333 if (slot == -1)
1334 return -1;
1335 slotp = reader_table + slot;
1337 /* Fire up the pcsc wrapper. We don't use any fork/exec code from
1338 the common directy but implement it direclty so that this file
1339 may still be source copied. */
1341 if (pipe (rp) == -1)
1343 log_error ("error creating a pipe: %s\n", strerror (errno));
1344 slotp->used = 0;
1345 return -1;
1347 if (pipe (wp) == -1)
1349 log_error ("error creating a pipe: %s\n", strerror (errno));
1350 close (rp[0]);
1351 close (rp[1]);
1352 slotp->used = 0;
1353 return -1;
1356 pid = fork ();
1357 if (pid == -1)
1359 log_error ("error forking process: %s\n", strerror (errno));
1360 close (rp[0]);
1361 close (rp[1]);
1362 close (wp[0]);
1363 close (wp[1]);
1364 slotp->used = 0;
1365 return -1;
1367 slotp->pcsc.pid = pid;
1369 if (!pid)
1370 { /*
1371 === Child ===
1374 /* Double fork. */
1375 pid = fork ();
1376 if (pid == -1)
1377 _exit (31);
1378 if (pid)
1379 _exit (0); /* Immediate exit this parent, so that the child
1380 gets cleaned up by the init process. */
1382 /* Connect our pipes. */
1383 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1384 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1385 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1386 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1388 /* Send stderr to the bit bucket. */
1389 fd = open ("/dev/null", O_WRONLY);
1390 if (fd == -1)
1391 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1392 if (fd != 2 && dup2 (fd, 2) == -1)
1393 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1395 /* Close all other files. */
1396 n = sysconf (_SC_OPEN_MAX);
1397 if (n < 0)
1398 n = MAX_OPEN_FDS;
1399 for (i=3; i < n; i++)
1400 close(i);
1401 errno = 0;
1403 execl (GNUPG_LIBDIR "/pcsc-wrapper",
1404 "pcsc-wrapper",
1405 "--",
1406 "1", /* API version */
1407 opt.pcsc_driver, /* Name of the PC/SC library. */
1408 NULL);
1409 _exit (31);
1413 === Parent ===
1415 close (wp[0]);
1416 close (rp[1]);
1417 slotp->pcsc.req_fd = wp[1];
1418 slotp->pcsc.rsp_fd = rp[0];
1420 /* Wait for the intermediate child to terminate. */
1421 #ifdef USE_GNU_PTH
1422 #define WAIT pth_waitpid
1423 #else
1424 #define WAIT waitpid
1425 #endif
1426 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1428 #undef X
1430 /* Now send the open request. */
1431 msgbuf[0] = 0x01; /* OPEN command. */
1432 len = portstr? strlen (portstr):0;
1433 msgbuf[1] = (len >> 24);
1434 msgbuf[2] = (len >> 16);
1435 msgbuf[3] = (len >> 8);
1436 msgbuf[4] = (len );
1437 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1438 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1440 log_error ("error sending PC/SC OPEN request: %s\n",
1441 strerror (errno));
1442 goto command_failed;
1444 /* Read the response. */
1445 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1447 log_error ("error receiving PC/SC OPEN response: %s\n",
1448 i? strerror (errno) : "premature EOF");
1449 goto command_failed;
1451 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1452 if (msgbuf[0] != 0x81 || len < 4)
1454 log_error ("invalid response header from PC/SC received\n");
1455 goto command_failed;
1457 len -= 4; /* Already read the error code. */
1458 if (len > DIM (slotp->atr))
1460 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1461 (unsigned long)len);
1462 goto command_failed;
1464 err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1465 if (err)
1467 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1468 sw = pcsc_error_to_sw (err);
1469 goto command_failed;
1472 slotp->last_status = 0;
1474 /* The open request may return a zero for the ATR length to
1475 indicate that no card is present. */
1476 n = len;
1477 if (n)
1479 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1481 log_error ("error receiving PC/SC OPEN response: %s\n",
1482 i? strerror (errno) : "premature EOF");
1483 goto command_failed;
1485 /* If we got to here we know that a card is present
1486 and usable. Thus remember this. */
1487 slotp->last_status = (1|2|4| 0x8000);
1489 slotp->atrlen = len;
1491 reader_table[slot].close_reader = close_pcsc_reader;
1492 reader_table[slot].reset_reader = reset_pcsc_reader;
1493 reader_table[slot].get_status_reader = pcsc_get_status;
1494 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1495 reader_table[slot].check_keypad = NULL;
1496 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1498 /* Read the status so that IS_T0 will be set. */
1499 pcsc_get_status (slot, &dummy_status);
1501 dump_reader_status (slot);
1502 return slot;
1504 command_failed:
1505 close (slotp->pcsc.req_fd);
1506 close (slotp->pcsc.rsp_fd);
1507 slotp->pcsc.req_fd = -1;
1508 slotp->pcsc.rsp_fd = -1;
1509 kill (slotp->pcsc.pid, SIGTERM);
1510 slotp->pcsc.pid = (pid_t)(-1);
1511 slotp->used = 0;
1512 /* There is no way to return SW. */
1513 return -1;
1515 #else /*!NEED_PCSC_WRAPPER */
1516 long err;
1517 int slot;
1518 char *list = NULL;
1519 unsigned long nreader, listlen, atrlen;
1520 char *p;
1521 unsigned long card_state, card_protocol;
1523 slot = new_reader_slot ();
1524 if (slot == -1)
1525 return -1;
1527 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1528 &reader_table[slot].pcsc.context);
1529 if (err)
1531 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1532 pcsc_error_string (err), err);
1533 reader_table[slot].used = 0;
1534 return -1;
1537 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1538 NULL, NULL, &nreader);
1539 if (!err)
1541 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1542 if (!list)
1544 log_error ("error allocating memory for reader list\n");
1545 pcsc_release_context (reader_table[slot].pcsc.context);
1546 reader_table[slot].used = 0;
1547 return -1 /*SW_HOST_OUT_OF_CORE*/;
1549 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1550 NULL, list, &nreader);
1552 if (err)
1554 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1555 pcsc_error_string (err), err);
1556 pcsc_release_context (reader_table[slot].pcsc.context);
1557 reader_table[slot].used = 0;
1558 xfree (list);
1559 return -1 /*pcsc_error_to_sw (err)*/;
1562 listlen = nreader;
1563 p = list;
1564 while (nreader)
1566 if (!*p && !p[1])
1567 break;
1568 if (*p)
1569 log_info ("detected reader `%s'\n", p);
1570 if (nreader < (strlen (p)+1))
1572 log_error ("invalid response from pcsc_list_readers\n");
1573 break;
1575 nreader -= strlen (p)+1;
1576 p += strlen (p) + 1;
1579 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1580 if (!reader_table[slot].rdrname)
1582 log_error ("error allocating memory for reader name\n");
1583 pcsc_release_context (reader_table[slot].pcsc.context);
1584 reader_table[slot].used = 0;
1585 return -1 /*SW_HOST_OUT_OF_CORE*/;
1587 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1588 xfree (list);
1589 list = NULL;
1591 err = pcsc_connect (reader_table[slot].pcsc.context,
1592 reader_table[slot].rdrname,
1593 PCSC_SHARE_EXCLUSIVE,
1594 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1595 &reader_table[slot].pcsc.card,
1596 &reader_table[slot].pcsc.protocol);
1597 if (err == PCSC_E_NO_SMARTCARD)
1598 reader_table[slot].pcsc.card = 0;
1599 else if (err)
1601 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1602 pcsc_error_string (err), err);
1603 pcsc_release_context (reader_table[slot].pcsc.context);
1604 xfree (reader_table[slot].rdrname);
1605 reader_table[slot].rdrname = NULL;
1606 reader_table[slot].used = 0;
1607 return -1 /*pcsc_error_to_sw (err)*/;
1610 reader_table[slot].atrlen = 0;
1611 reader_table[slot].last_status = 0;
1612 if (!err)
1614 char reader[250];
1615 unsigned long readerlen;
1617 atrlen = 32;
1618 readerlen = sizeof reader -1 ;
1619 err = pcsc_status (reader_table[slot].pcsc.card,
1620 reader, &readerlen,
1621 &card_state, &card_protocol,
1622 reader_table[slot].atr, &atrlen);
1623 if (err)
1624 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1625 pcsc_error_string (err), err, readerlen);
1626 else
1628 if (atrlen >= DIM (reader_table[0].atr))
1629 log_bug ("ATR returned by pcsc_status is too large\n");
1630 reader_table[slot].atrlen = atrlen;
1631 /* If we got to here we know that a card is present
1632 and usable. Thus remember this. */
1633 reader_table[slot].last_status = (1|2|4| 0x8000);
1634 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1638 reader_table[slot].close_reader = close_pcsc_reader;
1639 reader_table[slot].reset_reader = reset_pcsc_reader;
1640 reader_table[slot].get_status_reader = pcsc_get_status;
1641 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1642 reader_table[slot].check_keypad = NULL;
1643 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1645 /* log_debug ("state from pcsc_status: 0x%lx\n", card_state); */
1646 /* log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
1648 dump_reader_status (slot);
1649 return slot;
1650 #endif /*!NEED_PCSC_WRAPPER */
1656 #ifdef HAVE_LIBUSB
1658 Internal CCID driver interface.
1662 static void
1663 dump_ccid_reader_status (int slot)
1665 log_info ("reader slot %d: using ccid driver\n", slot);
1668 static int
1669 close_ccid_reader (int slot)
1671 ccid_close_reader (reader_table[slot].ccid.handle);
1672 reader_table[slot].used = 0;
1673 return 0;
1677 static int
1678 shutdown_ccid_reader (int slot)
1680 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1681 return 0;
1685 static int
1686 reset_ccid_reader (int slot)
1688 int err;
1689 reader_table_t slotp = reader_table + slot;
1690 unsigned char atr[33];
1691 size_t atrlen;
1693 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1694 if (err)
1695 return err;
1696 /* If the reset was successful, update the ATR. */
1697 assert (sizeof slotp->atr >= sizeof atr);
1698 slotp->atrlen = atrlen;
1699 memcpy (slotp->atr, atr, atrlen);
1700 dump_reader_status (slot);
1701 return 0;
1705 static int
1706 get_status_ccid (int slot, unsigned int *status)
1708 int rc;
1709 int bits;
1711 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1712 if (rc)
1713 return -1;
1715 if (bits == 0)
1716 *status = 1|2|4;
1717 else if (bits == 1)
1718 *status = 2;
1719 else
1720 *status = 0;
1722 return 0;
1726 /* Actually send the APDU of length APDULEN to SLOT and return a
1727 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1728 set to BUFLEN. Returns: Internal CCID driver error code. */
1729 static int
1730 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1731 unsigned char *buffer, size_t *buflen,
1732 struct pininfo_s *pininfo)
1734 long err;
1735 size_t maxbuflen;
1737 /* If we don't have an ATR, we need to reset the reader first. */
1738 if (!reader_table[slot].atrlen
1739 && (err = reset_ccid_reader (slot)))
1740 return err;
1742 if (DBG_CARD_IO)
1743 log_printhex (" APDU_data:", apdu, apdulen);
1745 maxbuflen = *buflen;
1746 if (pininfo)
1747 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1748 apdu, apdulen,
1749 pininfo->mode,
1750 pininfo->minlen,
1751 pininfo->maxlen,
1752 pininfo->padlen,
1753 buffer, maxbuflen, buflen);
1754 else
1755 err = ccid_transceive (reader_table[slot].ccid.handle,
1756 apdu, apdulen,
1757 buffer, maxbuflen, buflen);
1758 if (err)
1759 log_error ("ccid_transceive failed: (0x%lx)\n",
1760 err);
1762 return err;
1766 /* Check whether the CCID reader supports the ISO command code COMMAND
1767 on the keypad. Return 0 on success. For a description of the pin
1768 parameters, see ccid-driver.c */
1769 static int
1770 check_ccid_keypad (int slot, int command, int pin_mode,
1771 int pinlen_min, int pinlen_max, int pin_padlen)
1773 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1775 apdu[1] = command;
1776 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1777 apdu, sizeof apdu,
1778 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1779 NULL, 0, NULL);
1783 /* Open the reader and try to read an ATR. */
1784 static int
1785 open_ccid_reader (const char *portstr)
1787 int err;
1788 int slot;
1789 reader_table_t slotp;
1791 slot = new_reader_slot ();
1792 if (slot == -1)
1793 return -1;
1794 slotp = reader_table + slot;
1796 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1797 if (err)
1799 slotp->used = 0;
1800 return -1;
1803 err = ccid_get_atr (slotp->ccid.handle,
1804 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1805 if (err)
1807 slotp->atrlen = 0;
1808 err = 0;
1810 else
1812 /* If we got to here we know that a card is present
1813 and usable. Thus remember this. */
1814 reader_table[slot].last_status = (1|2|4| 0x8000);
1817 reader_table[slot].close_reader = close_ccid_reader;
1818 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1819 reader_table[slot].reset_reader = reset_ccid_reader;
1820 reader_table[slot].get_status_reader = get_status_ccid;
1821 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1822 reader_table[slot].check_keypad = check_ccid_keypad;
1823 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1825 dump_reader_status (slot);
1826 return slot;
1831 #endif /* HAVE_LIBUSB */
1835 #ifdef USE_G10CODE_RAPDU
1837 The Remote APDU Interface.
1839 This uses the Remote APDU protocol to contact a reader.
1841 The port number is actually an index into the list of ports as
1842 returned via the protocol.
1846 static int
1847 rapdu_status_to_sw (int status)
1849 int rc;
1851 switch (status)
1853 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1855 case RAPDU_STATUS_INVCMD:
1856 case RAPDU_STATUS_INVPROT:
1857 case RAPDU_STATUS_INVSEQ:
1858 case RAPDU_STATUS_INVCOOKIE:
1859 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1861 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1862 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1863 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1864 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1865 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1866 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1868 default: rc = SW_HOST_GENERAL_ERROR; break;
1871 return rc;
1876 static int
1877 close_rapdu_reader (int slot)
1879 rapdu_release (reader_table[slot].rapdu.handle);
1880 reader_table[slot].used = 0;
1881 return 0;
1885 static int
1886 reset_rapdu_reader (int slot)
1888 int err;
1889 reader_table_t slotp;
1890 rapdu_msg_t msg = NULL;
1892 slotp = reader_table + slot;
1894 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1895 if (err)
1897 log_error ("sending rapdu command RESET failed: %s\n",
1898 err < 0 ? strerror (errno): rapdu_strerror (err));
1899 rapdu_msg_release (msg);
1900 return rapdu_status_to_sw (err);
1902 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1903 if (err)
1905 log_error ("receiving rapdu message failed: %s\n",
1906 err < 0 ? strerror (errno): rapdu_strerror (err));
1907 rapdu_msg_release (msg);
1908 return rapdu_status_to_sw (err);
1910 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1912 int sw = rapdu_status_to_sw (msg->cmd);
1913 log_error ("rapdu command RESET failed: %s\n",
1914 rapdu_strerror (msg->cmd));
1915 rapdu_msg_release (msg);
1916 return sw;
1918 if (msg->datalen >= DIM (slotp->atr))
1920 log_error ("ATR returned by the RAPDU layer is too large\n");
1921 rapdu_msg_release (msg);
1922 return SW_HOST_INV_VALUE;
1924 slotp->atrlen = msg->datalen;
1925 memcpy (slotp->atr, msg->data, msg->datalen);
1927 rapdu_msg_release (msg);
1928 return 0;
1932 static int
1933 my_rapdu_get_status (int slot, unsigned int *status)
1935 int err;
1936 reader_table_t slotp;
1937 rapdu_msg_t msg = NULL;
1938 int oldslot;
1940 slotp = reader_table + slot;
1942 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
1943 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
1944 rapdu_set_reader (slotp->rapdu.handle, oldslot);
1945 if (err)
1947 log_error ("sending rapdu command GET_STATUS failed: %s\n",
1948 err < 0 ? strerror (errno): rapdu_strerror (err));
1949 return rapdu_status_to_sw (err);
1951 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1952 if (err)
1954 log_error ("receiving rapdu message failed: %s\n",
1955 err < 0 ? strerror (errno): rapdu_strerror (err));
1956 rapdu_msg_release (msg);
1957 return rapdu_status_to_sw (err);
1959 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1961 int sw = rapdu_status_to_sw (msg->cmd);
1962 log_error ("rapdu command GET_STATUS failed: %s\n",
1963 rapdu_strerror (msg->cmd));
1964 rapdu_msg_release (msg);
1965 return sw;
1967 *status = msg->data[0];
1969 rapdu_msg_release (msg);
1970 return 0;
1974 /* Actually send the APDU of length APDULEN to SLOT and return a
1975 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1976 set to BUFLEN. Returns: APDU error code. */
1977 static int
1978 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1979 unsigned char *buffer, size_t *buflen,
1980 struct pininfo_s *pininfo)
1982 int err;
1983 reader_table_t slotp;
1984 rapdu_msg_t msg = NULL;
1985 size_t maxlen = *buflen;
1987 slotp = reader_table + slot;
1989 *buflen = 0;
1990 if (DBG_CARD_IO)
1991 log_printhex (" APDU_data:", apdu, apdulen);
1993 if (apdulen < 4)
1995 log_error ("rapdu_send_apdu: APDU is too short\n");
1996 return SW_HOST_INV_VALUE;
1999 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2000 if (err)
2002 log_error ("sending rapdu command APDU failed: %s\n",
2003 err < 0 ? strerror (errno): rapdu_strerror (err));
2004 rapdu_msg_release (msg);
2005 return rapdu_status_to_sw (err);
2007 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2008 if (err)
2010 log_error ("receiving rapdu message failed: %s\n",
2011 err < 0 ? strerror (errno): rapdu_strerror (err));
2012 rapdu_msg_release (msg);
2013 return rapdu_status_to_sw (err);
2015 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2017 int sw = rapdu_status_to_sw (msg->cmd);
2018 log_error ("rapdu command APDU failed: %s\n",
2019 rapdu_strerror (msg->cmd));
2020 rapdu_msg_release (msg);
2021 return sw;
2024 if (msg->datalen > maxlen)
2026 log_error ("rapdu response apdu too large\n");
2027 rapdu_msg_release (msg);
2028 return SW_HOST_INV_VALUE;
2031 *buflen = msg->datalen;
2032 memcpy (buffer, msg->data, msg->datalen);
2034 rapdu_msg_release (msg);
2035 return 0;
2038 static int
2039 open_rapdu_reader (int portno,
2040 const unsigned char *cookie, size_t length,
2041 int (*readfnc) (void *opaque,
2042 void *buffer, size_t size),
2043 void *readfnc_value,
2044 int (*writefnc) (void *opaque,
2045 const void *buffer, size_t size),
2046 void *writefnc_value,
2047 void (*closefnc) (void *opaque),
2048 void *closefnc_value)
2050 int err;
2051 int slot;
2052 reader_table_t slotp;
2053 rapdu_msg_t msg = NULL;
2055 slot = new_reader_slot ();
2056 if (slot == -1)
2057 return -1;
2058 slotp = reader_table + slot;
2060 slotp->rapdu.handle = rapdu_new ();
2061 if (!slotp->rapdu.handle)
2063 slotp->used = 0;
2064 return -1;
2067 rapdu_set_reader (slotp->rapdu.handle, portno);
2069 rapdu_set_iofunc (slotp->rapdu.handle,
2070 readfnc, readfnc_value,
2071 writefnc, writefnc_value,
2072 closefnc, closefnc_value);
2073 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2075 /* First try to get the current ATR, but if the card is inactive
2076 issue a reset instead. */
2077 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2078 if (err == RAPDU_STATUS_NEEDRESET)
2079 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2080 if (err)
2082 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2083 err < 0 ? strerror (errno): rapdu_strerror (err));
2084 goto failure;
2086 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2087 if (err)
2089 log_info ("receiving rapdu message failed: %s\n",
2090 err < 0 ? strerror (errno): rapdu_strerror (err));
2091 goto failure;
2093 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2095 log_info ("rapdu command GET ATR failed: %s\n",
2096 rapdu_strerror (msg->cmd));
2097 goto failure;
2099 if (msg->datalen >= DIM (slotp->atr))
2101 log_error ("ATR returned by the RAPDU layer is too large\n");
2102 goto failure;
2104 slotp->atrlen = msg->datalen;
2105 memcpy (slotp->atr, msg->data, msg->datalen);
2107 reader_table[slot].close_reader = close_rapdu_reader;
2108 reader_table[slot].reset_reader = reset_rapdu_reader;
2109 reader_table[slot].get_status_reader = my_rapdu_get_status;
2110 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2111 reader_table[slot].check_keypad = NULL;
2112 reader_table[slot].dump_status_reader = NULL;
2114 dump_reader_status (slot);
2115 rapdu_msg_release (msg);
2116 return slot;
2118 failure:
2119 rapdu_msg_release (msg);
2120 rapdu_release (slotp->rapdu.handle);
2121 slotp->used = 0;
2122 return -1;
2125 #endif /*USE_G10CODE_RAPDU*/
2130 Driver Access
2134 static int
2135 lock_slot (int slot)
2137 #ifdef USE_GNU_PTH
2138 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2140 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2141 return SW_HOST_LOCKING_FAILED;
2143 #endif /*USE_GNU_PTH*/
2144 return 0;
2147 static int
2148 trylock_slot (int slot)
2150 #ifdef USE_GNU_PTH
2151 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2153 if (errno == EBUSY)
2154 return SW_HOST_BUSY;
2155 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2156 return SW_HOST_LOCKING_FAILED;
2158 #endif /*USE_GNU_PTH*/
2159 return 0;
2162 static void
2163 unlock_slot (int slot)
2165 #ifdef USE_GNU_PTH
2166 if (!pth_mutex_release (&reader_table[slot].lock))
2167 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2168 #endif /*USE_GNU_PTH*/
2172 /* Open the reader and return an internal slot number or -1 on
2173 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2174 the first USB reader. For PC/SC the first listed reader). */
2176 apdu_open_reader (const char *portstr)
2178 static int pcsc_api_loaded, ct_api_loaded;
2180 #ifdef HAVE_LIBUSB
2181 if (!opt.disable_ccid)
2183 int slot, i;
2184 const char *s;
2186 slot = open_ccid_reader (portstr);
2187 if (slot != -1)
2188 return slot; /* got one */
2190 /* If a CCID reader specification has been given, the user does
2191 not want a fallback to other drivers. */
2192 if (portstr)
2193 for (s=portstr, i=0; *s; s++)
2194 if (*s == ':' && (++i == 3))
2195 return -1;
2198 #endif /* HAVE_LIBUSB */
2200 if (opt.ctapi_driver && *opt.ctapi_driver)
2202 int port = portstr? atoi (portstr) : 32768;
2204 if (!ct_api_loaded)
2206 void *handle;
2208 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2209 if (!handle)
2211 log_error ("apdu_open_reader: failed to open driver: %s\n",
2212 dlerror ());
2213 return -1;
2215 CT_init = dlsym (handle, "CT_init");
2216 CT_data = dlsym (handle, "CT_data");
2217 CT_close = dlsym (handle, "CT_close");
2218 if (!CT_init || !CT_data || !CT_close)
2220 log_error ("apdu_open_reader: invalid CT-API driver\n");
2221 dlclose (handle);
2222 return -1;
2224 ct_api_loaded = 1;
2226 return open_ct_reader (port);
2230 /* No ctAPI configured, so lets try the PC/SC API */
2231 if (!pcsc_api_loaded)
2233 #ifndef NEED_PCSC_WRAPPER
2234 void *handle;
2236 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2237 if (!handle)
2239 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2240 opt.pcsc_driver, dlerror ());
2241 return -1;
2244 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2245 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2246 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2247 #if defined(_WIN32) || defined(__CYGWIN__)
2248 if (!pcsc_list_readers)
2249 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2250 #endif
2251 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2252 #if defined(_WIN32) || defined(__CYGWIN__)
2253 if (!pcsc_get_status_change)
2254 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2255 #endif
2256 pcsc_connect = dlsym (handle, "SCardConnect");
2257 #if defined(_WIN32) || defined(__CYGWIN__)
2258 if (!pcsc_connect)
2259 pcsc_connect = dlsym (handle, "SCardConnectA");
2260 #endif
2261 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2262 #if defined(_WIN32) || defined(__CYGWIN__)
2263 if (!pcsc_reconnect)
2264 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2265 #endif
2266 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2267 pcsc_status = dlsym (handle, "SCardStatus");
2268 #if defined(_WIN32) || defined(__CYGWIN__)
2269 if (!pcsc_status)
2270 pcsc_status = dlsym (handle, "SCardStatusA");
2271 #endif
2272 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2273 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2274 pcsc_transmit = dlsym (handle, "SCardTransmit");
2275 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2277 if (!pcsc_establish_context
2278 || !pcsc_release_context
2279 || !pcsc_list_readers
2280 || !pcsc_get_status_change
2281 || !pcsc_connect
2282 || !pcsc_reconnect
2283 || !pcsc_disconnect
2284 || !pcsc_status
2285 || !pcsc_begin_transaction
2286 || !pcsc_end_transaction
2287 || !pcsc_transmit
2288 /* || !pcsc_set_timeout */)
2290 /* Note that set_timeout is currently not used and also not
2291 available under Windows. */
2292 log_error ("apdu_open_reader: invalid PC/SC driver "
2293 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2294 !!pcsc_establish_context,
2295 !!pcsc_release_context,
2296 !!pcsc_list_readers,
2297 !!pcsc_get_status_change,
2298 !!pcsc_connect,
2299 !!pcsc_reconnect,
2300 !!pcsc_disconnect,
2301 !!pcsc_status,
2302 !!pcsc_begin_transaction,
2303 !!pcsc_end_transaction,
2304 !!pcsc_transmit,
2305 !!pcsc_set_timeout );
2306 dlclose (handle);
2307 return -1;
2309 #endif /*!NEED_PCSC_WRAPPER*/
2310 pcsc_api_loaded = 1;
2313 return open_pcsc_reader (portstr);
2317 /* Open an remote reader and return an internal slot number or -1 on
2318 error. This function is an alternative to apdu_open_reader and used
2319 with remote readers only. Note that the supplied CLOSEFNC will
2320 only be called once and the slot will not be valid afther this.
2322 If PORTSTR is NULL we default to the first availabe port.
2325 apdu_open_remote_reader (const char *portstr,
2326 const unsigned char *cookie, size_t length,
2327 int (*readfnc) (void *opaque,
2328 void *buffer, size_t size),
2329 void *readfnc_value,
2330 int (*writefnc) (void *opaque,
2331 const void *buffer, size_t size),
2332 void *writefnc_value,
2333 void (*closefnc) (void *opaque),
2334 void *closefnc_value)
2336 #ifdef USE_G10CODE_RAPDU
2337 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2338 cookie, length,
2339 readfnc, readfnc_value,
2340 writefnc, writefnc_value,
2341 closefnc, closefnc_value);
2342 #else
2343 #ifdef _WIN32
2344 errno = ENOENT;
2345 #else
2346 errno = ENOSYS;
2347 #endif
2348 return -1;
2349 #endif
2354 apdu_close_reader (int slot)
2356 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2357 return SW_HOST_NO_DRIVER;
2358 if (reader_table[slot].close_reader)
2359 return reader_table[slot].close_reader (slot);
2360 return SW_HOST_NOT_SUPPORTED;
2363 /* Shutdown a reader; that is basically the same as a close but keeps
2364 the handle ready for later use. A apdu_reset_header should be used
2365 to get it active again. */
2367 apdu_shutdown_reader (int slot)
2369 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2370 return SW_HOST_NO_DRIVER;
2371 if (reader_table[slot].shutdown_reader)
2372 return reader_table[slot].shutdown_reader (slot);
2373 return SW_HOST_NOT_SUPPORTED;
2376 /* Enumerate all readers and return information on whether this reader
2377 is in use. The caller should start with SLOT set to 0 and
2378 increment it with each call until an error is returned. */
2380 apdu_enum_reader (int slot, int *used)
2382 if (slot < 0 || slot >= MAX_READER)
2383 return SW_HOST_NO_DRIVER;
2384 *used = reader_table[slot].used;
2385 return 0;
2388 /* Do a reset for the card in reader at SLOT. */
2390 apdu_reset (int slot)
2392 int sw;
2394 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2395 return SW_HOST_NO_DRIVER;
2397 if ((sw = lock_slot (slot)))
2398 return sw;
2400 reader_table[slot].last_status = 0;
2401 if (reader_table[slot].reset_reader)
2402 sw = reader_table[slot].reset_reader (slot);
2404 if (!sw)
2406 /* If we got to here we know that a card is present
2407 and usable. Thus remember this. */
2408 reader_table[slot].last_status = (1|2|4| 0x8000);
2411 unlock_slot (slot);
2412 return sw;
2416 /* Activate a card if it has not yet been done. This is a kind of
2417 reset-if-required. It is useful to test for presence of a card
2418 before issuing a bunch of apdu commands. It does not wait on a
2419 locked card. */
2421 apdu_activate (int slot)
2423 int sw;
2424 unsigned int s;
2426 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2427 return SW_HOST_NO_DRIVER;
2429 if ((sw = trylock_slot (slot)))
2430 return sw;
2432 if (reader_table[slot].get_status_reader)
2433 sw = reader_table[slot].get_status_reader (slot, &s);
2435 if (!sw)
2437 if (!(s & 2)) /* Card not present. */
2438 sw = SW_HOST_NO_CARD;
2439 else if ( ((s & 2) && !(s & 4))
2440 || !reader_table[slot].atrlen )
2442 /* We don't have an ATR or a card is present though inactive:
2443 do a reset now. */
2444 if (reader_table[slot].reset_reader)
2446 reader_table[slot].last_status = 0;
2447 sw = reader_table[slot].reset_reader (slot);
2448 if (!sw)
2450 /* If we got to here we know that a card is present
2451 and usable. Thus remember this. */
2452 reader_table[slot].last_status = (1|2|4| 0x8000);
2458 unlock_slot (slot);
2459 return sw;
2464 unsigned char *
2465 apdu_get_atr (int slot, size_t *atrlen)
2467 unsigned char *buf;
2469 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2470 return NULL;
2472 buf = xtrymalloc (reader_table[slot].atrlen);
2473 if (!buf)
2474 return NULL;
2475 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2476 *atrlen = reader_table[slot].atrlen;
2477 return buf;
2482 /* Retrieve the status for SLOT. The function does only wait for the
2483 card to become available if HANG is set to true. On success the
2484 bits in STATUS will be set to
2486 bit 0 = card present and usable
2487 bit 1 = card present
2488 bit 2 = card active
2489 bit 3 = card access locked [not yet implemented]
2491 For must application, testing bit 0 is sufficient.
2493 CHANGED will receive the value of the counter tracking the number
2494 of card insertions. This value may be used to detect a card
2495 change.
2498 apdu_get_status (int slot, int hang,
2499 unsigned int *status, unsigned int *changed)
2501 int sw;
2502 unsigned int s;
2504 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2505 return SW_HOST_NO_DRIVER;
2507 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2508 return sw;
2510 if (reader_table[slot].get_status_reader)
2511 sw = reader_table[slot].get_status_reader (slot, &s);
2513 unlock_slot (slot);
2515 if (sw)
2517 reader_table[slot].last_status = 0;
2518 return sw;
2521 /* Keep track of changes. We use one extra bit to test whether we
2522 have checked the status at least once. */
2523 if ( s != (reader_table[slot].last_status & 0x07ff)
2524 || !reader_table[slot].last_status )
2526 reader_table[slot].change_counter++;
2527 /* Make sure that the ATR is invalid so that a reset will be by
2528 activate. */
2529 reader_table[slot].atrlen = 0;
2531 reader_table[slot].last_status = (s | 0x8000);
2533 if (status)
2534 *status = s;
2535 if (changed)
2536 *changed = reader_table[slot].change_counter;
2537 return 0;
2541 /* Check whether the reader supports the ISO command code COMMAND on
2542 the keypad. Return 0 on success. For a description of the pin
2543 parameters, see ccid-driver.c */
2545 apdu_check_keypad (int slot, int command, int pin_mode,
2546 int pinlen_min, int pinlen_max, int pin_padlen)
2548 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2549 return SW_HOST_NO_DRIVER;
2551 if (reader_table[slot].check_keypad)
2552 return reader_table[slot].check_keypad (slot, command,
2553 pin_mode, pinlen_min, pinlen_max,
2554 pin_padlen);
2555 else
2556 return SW_HOST_NOT_SUPPORTED;
2560 /* Dispatcher for the actual send_apdu function. Note, that this
2561 function should be called in locked state. */
2562 static int
2563 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2564 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2566 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2567 return SW_HOST_NO_DRIVER;
2569 if (reader_table[slot].send_apdu_reader)
2570 return reader_table[slot].send_apdu_reader (slot,
2571 apdu, apdulen,
2572 buffer, buflen, pininfo);
2573 else
2574 return SW_HOST_NOT_SUPPORTED;
2578 /* Core APDU trabceiver function. Parameters are described at
2579 apdu_send_le with the exception of PININFO which indicates keypad
2580 related operations if not NULL. */
2581 static int
2582 send_le (int slot, int class, int ins, int p0, int p1,
2583 int lc, const char *data, int le,
2584 unsigned char **retbuf, size_t *retbuflen,
2585 struct pininfo_s *pininfo)
2587 #define RESULTLEN 256
2588 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2589 the driver. */
2590 size_t resultlen;
2591 unsigned char apdu[5+256+1];
2592 size_t apdulen;
2593 int sw;
2594 long rc; /* we need a long here due to PC/SC. */
2596 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2597 return SW_HOST_NO_DRIVER;
2599 if (DBG_CARD_IO)
2600 log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
2601 class, ins, p0, p1, lc, le);
2603 if (lc != -1 && (lc > 255 || lc < 0))
2604 return SW_WRONG_LENGTH;
2605 if (le != -1 && (le > 256 || le < 0))
2606 return SW_WRONG_LENGTH;
2607 if ((!data && lc != -1) || (data && lc == -1))
2608 return SW_HOST_INV_VALUE;
2610 if ((sw = lock_slot (slot)))
2611 return sw;
2613 apdulen = 0;
2614 apdu[apdulen++] = class;
2615 apdu[apdulen++] = ins;
2616 apdu[apdulen++] = p0;
2617 apdu[apdulen++] = p1;
2618 if (lc != -1)
2620 apdu[apdulen++] = lc;
2621 memcpy (apdu+apdulen, data, lc);
2622 apdulen += lc;
2623 /* T=0 does not allow the use of Lc together with Le; thus
2624 disable Le in this case. */
2625 if (reader_table[slot].is_t0)
2626 le = -1;
2628 if (le != -1)
2629 apdu[apdulen++] = le; /* Truncation is okay because 0 means 256. */
2630 assert (sizeof (apdu) >= apdulen);
2631 /* As safeguard don't pass any garbage from the stack to the driver. */
2632 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2633 resultlen = RESULTLEN;
2634 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2635 if (rc || resultlen < 2)
2637 log_error ("apdu_send_simple(%d) failed: %s\n",
2638 slot, apdu_strerror (rc));
2639 unlock_slot (slot);
2640 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2642 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2643 /* store away the returned data but strip the statusword. */
2644 resultlen -= 2;
2645 if (DBG_CARD_IO)
2647 log_debug (" response: sw=%04X datalen=%d\n",
2648 sw, (unsigned int)resultlen);
2649 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2650 log_printhex (" dump: ", result, resultlen);
2653 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2655 if (retbuf)
2657 *retbuf = xtrymalloc (resultlen? resultlen : 1);
2658 if (!*retbuf)
2660 unlock_slot (slot);
2661 return SW_HOST_OUT_OF_CORE;
2663 *retbuflen = resultlen;
2664 memcpy (*retbuf, result, resultlen);
2667 else if ((sw & 0xff00) == SW_MORE_DATA)
2669 unsigned char *p = NULL, *tmp;
2670 size_t bufsize = 4096;
2672 /* It is likely that we need to return much more data, so we
2673 start off with a large buffer. */
2674 if (retbuf)
2676 *retbuf = p = xtrymalloc (bufsize);
2677 if (!*retbuf)
2679 unlock_slot (slot);
2680 return SW_HOST_OUT_OF_CORE;
2682 assert (resultlen < bufsize);
2683 memcpy (p, result, resultlen);
2684 p += resultlen;
2689 int len = (sw & 0x00ff);
2691 if (DBG_CARD_IO)
2692 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2693 slot, len);
2694 apdulen = 0;
2695 apdu[apdulen++] = class;
2696 apdu[apdulen++] = 0xC0;
2697 apdu[apdulen++] = 0;
2698 apdu[apdulen++] = 0;
2699 apdu[apdulen++] = len;
2700 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2701 resultlen = RESULTLEN;
2702 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2703 if (rc || resultlen < 2)
2705 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2706 slot, apdu_strerror (rc));
2707 unlock_slot (slot);
2708 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2710 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2711 resultlen -= 2;
2712 if (DBG_CARD_IO)
2714 log_debug (" more: sw=%04X datalen=%d\n",
2715 sw, (unsigned int)resultlen);
2716 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2717 log_printhex (" dump: ", result, resultlen);
2720 if ((sw & 0xff00) == SW_MORE_DATA
2721 || sw == SW_SUCCESS
2722 || sw == SW_EOF_REACHED )
2724 if (retbuf && resultlen)
2726 if (p - *retbuf + resultlen > bufsize)
2728 bufsize += resultlen > 4096? resultlen: 4096;
2729 tmp = xtryrealloc (*retbuf, bufsize);
2730 if (!tmp)
2732 unlock_slot (slot);
2733 return SW_HOST_OUT_OF_CORE;
2735 p = tmp + (p - *retbuf);
2736 *retbuf = tmp;
2738 memcpy (p, result, resultlen);
2739 p += resultlen;
2742 else
2743 log_info ("apdu_send_simple(%d) "
2744 "got unexpected status %04X from get response\n",
2745 slot, sw);
2747 while ((sw & 0xff00) == SW_MORE_DATA);
2749 if (retbuf)
2751 *retbuflen = p - *retbuf;
2752 tmp = xtryrealloc (*retbuf, *retbuflen);
2753 if (tmp)
2754 *retbuf = tmp;
2758 unlock_slot (slot);
2760 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2761 log_printhex (" dump: ", *retbuf, *retbuflen);
2763 return sw;
2764 #undef RESULTLEN
2767 /* Send an APDU to the card in SLOT. The APDU is created from all
2768 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2769 for LC won't sent this field and the data field; in this case DATA
2770 must also be passed as NULL. The return value is the status word
2771 or -1 for an invalid SLOT or other non card related error. If
2772 RETBUF is not NULL, it will receive an allocated buffer with the
2773 returned data. The length of that data will be put into
2774 *RETBUFLEN. The caller is reponsible for releasing the buffer even
2775 in case of errors. */
2777 apdu_send_le(int slot, int class, int ins, int p0, int p1,
2778 int lc, const char *data, int le,
2779 unsigned char **retbuf, size_t *retbuflen)
2781 return send_le (slot, class, ins, p0, p1,
2782 lc, data, le,
2783 retbuf, retbuflen,
2784 NULL);
2788 /* Send an APDU to the card in SLOT. The APDU is created from all
2789 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2790 LC won't sent this field and the data field; in this case DATA must
2791 also be passed as NULL. The return value is the status word or -1
2792 for an invalid SLOT or other non card related error. If RETBUF is
2793 not NULL, it will receive an allocated buffer with the returned
2794 data. The length of that data will be put into *RETBUFLEN. The
2795 caller is reponsible for releasing the buffer even in case of
2796 errors. */
2798 apdu_send (int slot, int class, int ins, int p0, int p1,
2799 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2801 return send_le (slot, class, ins, p0, p1, lc, data, 256,
2802 retbuf, retbuflen, NULL);
2805 /* Send an APDU to the card in SLOT. The APDU is created from all
2806 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2807 LC won't sent this field and the data field; in this case DATA must
2808 also be passed as NULL. The return value is the status word or -1
2809 for an invalid SLOT or other non card related error. No data will be
2810 returned. */
2812 apdu_send_simple (int slot, int class, int ins, int p0, int p1,
2813 int lc, const char *data)
2815 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL);
2819 /* Same as apdu_send_simple but uses the keypad of the reader. */
2821 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
2822 int lc, const char *data,
2823 int pin_mode,
2824 int pinlen_min, int pinlen_max, int pin_padlen)
2826 struct pininfo_s pininfo;
2828 pininfo.mode = pin_mode;
2829 pininfo.minlen = pinlen_min;
2830 pininfo.maxlen = pinlen_max;
2831 pininfo.padlen = pin_padlen;
2832 return send_le (slot, class, ins, p0, p1, lc, data, -1,
2833 NULL, NULL, &pininfo);
2837 /* This is a more generic version of the apdu sending routine. It
2838 takes an already formatted APDU in APDUDATA or length APDUDATALEN
2839 and returns the with the APDU including the status word. With
2840 HANDLE_MORE set to true this function will handle the MORE DATA
2841 status and return all APDUs concatenated with one status word at
2842 the end. The function does not return a regular status word but 0
2843 on success. If the slot is locked, the fucntion returns
2844 immediately.*/
2846 apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
2847 int handle_more,
2848 unsigned char **retbuf, size_t *retbuflen)
2850 #define RESULTLEN 256
2851 unsigned char apdu[5+256+1];
2852 size_t apdulen;
2853 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2854 the driver. */
2855 size_t resultlen;
2856 int sw;
2857 long rc; /* we need a long here due to PC/SC. */
2858 int class;
2860 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2861 return SW_HOST_NO_DRIVER;
2863 if ((sw = trylock_slot (slot)))
2864 return sw;
2866 /* We simply trunctate a too long APDU. */
2867 if (apdudatalen > sizeof apdu)
2868 apdudatalen = sizeof apdu;
2869 apdulen = apdudatalen;
2870 memcpy (apdu, apdudata, apdudatalen);
2871 class = apdulen? *apdu : 0;
2873 resultlen = RESULTLEN;
2874 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2875 if (rc || resultlen < 2)
2877 log_error ("apdu_send_direct(%d) failed: %s\n",
2878 slot, apdu_strerror (rc));
2879 unlock_slot (slot);
2880 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2882 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2883 /* Store away the returned data but strip the statusword. */
2884 resultlen -= 2;
2885 if (DBG_CARD_IO)
2887 log_debug (" response: sw=%04X datalen=%d\n",
2888 sw, (unsigned int)resultlen);
2889 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2890 log_printhex (" dump: ", result, resultlen);
2893 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
2895 unsigned char *p = NULL, *tmp;
2896 size_t bufsize = 4096;
2898 /* It is likely that we need to return much more data, so we
2899 start off with a large buffer. */
2900 if (retbuf)
2902 *retbuf = p = xtrymalloc (bufsize + 2);
2903 if (!*retbuf)
2905 unlock_slot (slot);
2906 return SW_HOST_OUT_OF_CORE;
2908 assert (resultlen < bufsize);
2909 memcpy (p, result, resultlen);
2910 p += resultlen;
2915 int len = (sw & 0x00ff);
2917 if (DBG_CARD_IO)
2918 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
2919 slot, len);
2920 apdulen = 0;
2921 apdu[apdulen++] = class;
2922 apdu[apdulen++] = 0xC0;
2923 apdu[apdulen++] = 0;
2924 apdu[apdulen++] = 0;
2925 apdu[apdulen++] = len;
2926 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2927 resultlen = RESULTLEN;
2928 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2929 if (rc || resultlen < 2)
2931 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
2932 slot, apdu_strerror (rc));
2933 unlock_slot (slot);
2934 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2936 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2937 resultlen -= 2;
2938 if (DBG_CARD_IO)
2940 log_debug (" more: sw=%04X datalen=%d\n",
2941 sw, (unsigned int)resultlen);
2942 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2943 log_printhex (" dump: ", result, resultlen);
2946 if ((sw & 0xff00) == SW_MORE_DATA
2947 || sw == SW_SUCCESS
2948 || sw == SW_EOF_REACHED )
2950 if (retbuf && resultlen)
2952 if (p - *retbuf + resultlen > bufsize)
2954 bufsize += resultlen > 4096? resultlen: 4096;
2955 tmp = xtryrealloc (*retbuf, bufsize + 2);
2956 if (!tmp)
2958 unlock_slot (slot);
2959 return SW_HOST_OUT_OF_CORE;
2961 p = tmp + (p - *retbuf);
2962 *retbuf = tmp;
2964 memcpy (p, result, resultlen);
2965 p += resultlen;
2968 else
2969 log_info ("apdu_send_sdirect(%d) "
2970 "got unexpected status %04X from get response\n",
2971 slot, sw);
2973 while ((sw & 0xff00) == SW_MORE_DATA);
2975 if (retbuf)
2977 *retbuflen = p - *retbuf;
2978 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
2979 if (tmp)
2980 *retbuf = tmp;
2983 else
2985 if (retbuf)
2987 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
2988 if (!*retbuf)
2990 unlock_slot (slot);
2991 return SW_HOST_OUT_OF_CORE;
2993 *retbuflen = resultlen;
2994 memcpy (*retbuf, result, resultlen);
2998 unlock_slot (slot);
3000 /* Append the status word - we reseved the two extra bytes while
3001 allocating the buffer. */
3002 if (retbuf)
3004 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3005 (*retbuf)[(*retbuflen)++] = sw;
3008 if (DBG_CARD_IO && retbuf)
3009 log_printhex (" dump: ", *retbuf, *retbuflen);
3011 return 0;
3012 #undef RESULTLEN