2007-09-14 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / apdu.c
blobe2d43bd9d301d3e7dbc8188d228a175aa26fd903
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 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 * $Id$
22 /* NOTE: This module is also used by other software, thus the use of
23 the macro USE_GNU_PTH is mandatory. For GnuPG this macro is
24 guaranteed to be defined true. */
26 #include <config.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <signal.h>
33 #ifdef USE_GNU_PTH
34 # include <unistd.h>
35 # include <fcntl.h>
36 # include <pth.h>
37 #endif
40 /* If requested include the definitions for the remote APDU protocol
41 code. */
42 #ifdef USE_G10CODE_RAPDU
43 #include "rapdu.h"
44 #endif /*USE_G10CODE_RAPDU*/
46 #if defined(GNUPG_SCD_MAIN_HEADER)
47 #include GNUPG_SCD_MAIN_HEADER
48 #elif GNUPG_MAJOR_VERSION == 1
49 /* This is used with GnuPG version < 1.9. The code has been source
50 copied from the current GnuPG >= 1.9 and is maintained over
51 there. */
52 #include "options.h"
53 #include "errors.h"
54 #include "memory.h"
55 #include "util.h"
56 #include "i18n.h"
57 #include "cardglue.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
59 #include "scdaemon.h"
60 #endif /* GNUPG_MAJOR_VERSION != 1 */
62 #include "apdu.h"
63 #include "ccid-driver.h"
66 /* Due to conflicting use of threading libraries we usually can't link
67 against libpcsclite. Instead we use a wrapper program. */
68 #ifdef USE_GNU_PTH
69 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
70 #define NEED_PCSC_WRAPPER 1
71 #endif
72 #endif
75 #define MAX_READER 4 /* Number of readers we support concurrently. */
78 #if defined(_WIN32) || defined(__CYGWIN__)
79 #define DLSTDCALL __stdcall
80 #else
81 #define DLSTDCALL
82 #endif
84 #ifdef _POSIX_OPEN_MAX
85 #define MAX_OPEN_FDS _POSIX_OPEN_MAX
86 #else
87 #define MAX_OPEN_FDS 20
88 #endif
90 /* Helper to pass parameters related to keypad based operations. */
91 struct pininfo_s
93 int mode;
94 int minlen;
95 int maxlen;
96 int padlen;
99 /* A structure to collect information pertaining to one reader
100 slot. */
101 struct reader_table_s {
102 int used; /* True if slot is used. */
103 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
105 /* Function pointers intialized to the various backends. */
106 int (*close_reader)(int);
107 int (*shutdown_reader)(int);
108 int (*reset_reader)(int);
109 int (*get_status_reader)(int, unsigned int *);
110 int (*send_apdu_reader)(int,unsigned char *,size_t,
111 unsigned char *, size_t *, struct pininfo_s *);
112 int (*check_keypad)(int, int, int, int, int, int);
113 void (*dump_status_reader)(int);
115 struct {
116 ccid_driver_t handle;
117 } ccid;
118 struct {
119 unsigned long context;
120 unsigned long card;
121 unsigned long protocol;
122 #ifdef NEED_PCSC_WRAPPER
123 int req_fd;
124 int rsp_fd;
125 pid_t pid;
126 #endif /*NEED_PCSC_WRAPPER*/
127 } pcsc;
128 #ifdef USE_G10CODE_RAPDU
129 struct {
130 rapdu_t handle;
131 } rapdu;
132 #endif /*USE_G10CODE_RAPDU*/
133 char *rdrname; /* Name of the connected reader or NULL if unknown. */
134 int last_status;
135 int status;
136 int is_t0; /* True if we know that we are running T=0. */
137 unsigned char atr[33];
138 size_t atrlen; /* A zero length indicates that the ATR has
139 not yet been read; i.e. the card is not
140 ready for use. */
141 unsigned int change_counter;
142 #ifdef USE_GNU_PTH
143 int lock_initialized;
144 pth_mutex_t lock;
145 #endif
147 typedef struct reader_table_s *reader_table_t;
149 /* A global table to keep track of active readers. */
150 static struct reader_table_s reader_table[MAX_READER];
153 /* ct API function pointer. */
154 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
155 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
156 unsigned char *sad, unsigned short lc,
157 unsigned char *cmd, unsigned short *lr,
158 unsigned char *rsp);
159 static char (* DLSTDCALL CT_close) (unsigned short ctn);
161 /* PC/SC constants and function pointer. */
162 #define PCSC_SCOPE_USER 0
163 #define PCSC_SCOPE_TERMINAL 1
164 #define PCSC_SCOPE_SYSTEM 2
165 #define PCSC_SCOPE_GLOBAL 3
167 #define PCSC_PROTOCOL_T0 1
168 #define PCSC_PROTOCOL_T1 2
169 #define PCSC_PROTOCOL_RAW 4
171 #define PCSC_SHARE_EXCLUSIVE 1
172 #define PCSC_SHARE_SHARED 2
173 #define PCSC_SHARE_DIRECT 3
175 #define PCSC_LEAVE_CARD 0
176 #define PCSC_RESET_CARD 1
177 #define PCSC_UNPOWER_CARD 2
178 #define PCSC_EJECT_CARD 3
180 #define PCSC_UNKNOWN 0x0001
181 #define PCSC_ABSENT 0x0002 /* Card is absent. */
182 #define PCSC_PRESENT 0x0004 /* Card is present. */
183 #define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
184 #define PCSC_POWERED 0x0010 /* Card is powered. */
185 #define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
186 #define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
188 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
189 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
190 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
191 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
192 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
193 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
194 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
195 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
196 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
197 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
198 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
200 /* Some PC/SC error codes. */
201 #define PCSC_E_CANCELLED 0x80100002
202 #define PCSC_E_CANT_DISPOSE 0x8010000E
203 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
204 #define PCSC_E_INVALID_ATR 0x80100015
205 #define PCSC_E_INVALID_HANDLE 0x80100003
206 #define PCSC_E_INVALID_PARAMETER 0x80100004
207 #define PCSC_E_INVALID_TARGET 0x80100005
208 #define PCSC_E_INVALID_VALUE 0x80100011
209 #define PCSC_E_NO_MEMORY 0x80100006
210 #define PCSC_E_UNKNOWN_READER 0x80100009
211 #define PCSC_E_TIMEOUT 0x8010000A
212 #define PCSC_E_SHARING_VIOLATION 0x8010000B
213 #define PCSC_E_NO_SMARTCARD 0x8010000C
214 #define PCSC_E_UNKNOWN_CARD 0x8010000D
215 #define PCSC_E_PROTO_MISMATCH 0x8010000F
216 #define PCSC_E_NOT_READY 0x80100010
217 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
218 #define PCSC_E_NOT_TRANSACTED 0x80100016
219 #define PCSC_E_READER_UNAVAILABLE 0x80100017
220 #define PCSC_W_REMOVED_CARD 0x80100069
222 /* The PC/SC error is defined as a long as per specs. Due to left
223 shifts bit 31 will get sign extended. We use this mask to fix
224 it. */
225 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
228 struct pcsc_io_request_s
230 unsigned long protocol;
231 unsigned long pci_len;
234 typedef struct pcsc_io_request_s *pcsc_io_request_t;
236 struct pcsc_readerstate_s
238 const char *reader;
239 void *user_data;
240 unsigned long current_state;
241 unsigned long event_state;
242 unsigned long atrlen;
243 unsigned char atr[33];
246 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
248 long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
249 const void *reserved1,
250 const void *reserved2,
251 unsigned long *r_context);
252 long (* DLSTDCALL pcsc_release_context) (unsigned long context);
253 long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
254 const char *groups,
255 char *readers, unsigned long*readerslen);
256 long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
257 unsigned long timeout,
258 pcsc_readerstate_t readerstates,
259 unsigned long nreaderstates);
260 long (* DLSTDCALL pcsc_connect) (unsigned long context,
261 const char *reader,
262 unsigned long share_mode,
263 unsigned long preferred_protocols,
264 unsigned long *r_card,
265 unsigned long *r_active_protocol);
266 long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
267 unsigned long share_mode,
268 unsigned long preferred_protocols,
269 unsigned long initialization,
270 unsigned long *r_active_protocol);
271 long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
272 unsigned long disposition);
273 long (* DLSTDCALL pcsc_status) (unsigned long card,
274 char *reader, unsigned long *readerlen,
275 unsigned long *r_state,
276 unsigned long *r_protocol,
277 unsigned char *atr, unsigned long *atrlen);
278 long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
279 long (* DLSTDCALL pcsc_end_transaction) (unsigned long card,
280 unsigned long disposition);
281 long (* DLSTDCALL pcsc_transmit) (unsigned long card,
282 const pcsc_io_request_t send_pci,
283 const unsigned char *send_buffer,
284 unsigned long send_len,
285 pcsc_io_request_t recv_pci,
286 unsigned char *recv_buffer,
287 unsigned long *recv_len);
288 long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
289 unsigned long timeout);
292 /* Prototypes. */
293 static int pcsc_get_status (int slot, unsigned int *status);
298 Helper
302 /* Find an unused reader slot for PORTSTR and put it into the reader
303 table. Return -1 on error or the index into the reader table. */
304 static int
305 new_reader_slot (void)
307 int i, reader = -1;
309 for (i=0; i < MAX_READER; i++)
311 if (!reader_table[i].used && reader == -1)
312 reader = i;
314 if (reader == -1)
316 log_error ("new_reader_slot: out of slots\n");
317 return -1;
319 #ifdef USE_GNU_PTH
320 if (!reader_table[reader].lock_initialized)
322 if (!pth_mutex_init (&reader_table[reader].lock))
324 log_error ("error initializing mutex: %s\n", strerror (errno));
325 return -1;
327 reader_table[reader].lock_initialized = 1;
329 #endif /*USE_GNU_PTH*/
330 reader_table[reader].close_reader = NULL;
331 reader_table[reader].shutdown_reader = NULL;
332 reader_table[reader].reset_reader = NULL;
333 reader_table[reader].get_status_reader = NULL;
334 reader_table[reader].send_apdu_reader = NULL;
335 reader_table[reader].check_keypad = NULL;
336 reader_table[reader].dump_status_reader = NULL;
338 reader_table[reader].used = 1;
339 reader_table[reader].last_status = 0;
340 reader_table[reader].is_t0 = 1;
341 #ifdef NEED_PCSC_WRAPPER
342 reader_table[reader].pcsc.req_fd = -1;
343 reader_table[reader].pcsc.rsp_fd = -1;
344 reader_table[reader].pcsc.pid = (pid_t)(-1);
345 #endif
347 return reader;
351 static void
352 dump_reader_status (int slot)
354 if (!opt.verbose)
355 return;
357 if (reader_table[slot].dump_status_reader)
358 reader_table[slot].dump_status_reader (slot);
360 if (reader_table[slot].status != -1
361 && reader_table[slot].atrlen)
363 log_info ("slot %d: ATR=", slot);
364 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
370 static const char *
371 host_sw_string (long err)
373 switch (err)
375 case 0: return "okay";
376 case SW_HOST_OUT_OF_CORE: return "out of core";
377 case SW_HOST_INV_VALUE: return "invalid value";
378 case SW_HOST_NO_DRIVER: return "no driver";
379 case SW_HOST_NOT_SUPPORTED: return "not supported";
380 case SW_HOST_LOCKING_FAILED: return "locking failed";
381 case SW_HOST_BUSY: return "busy";
382 case SW_HOST_NO_CARD: return "no card";
383 case SW_HOST_CARD_INACTIVE: return "card inactive";
384 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
385 case SW_HOST_GENERAL_ERROR: return "general error";
386 case SW_HOST_NO_READER: return "no reader";
387 case SW_HOST_ABORTED: return "aborted";
388 case SW_HOST_NO_KEYPAD: return "no keypad";
389 default: return "unknown host status error";
394 const char *
395 apdu_strerror (int rc)
397 switch (rc)
399 case SW_EOF_REACHED : return "eof reached";
400 case SW_EEPROM_FAILURE : return "eeprom failure";
401 case SW_WRONG_LENGTH : return "wrong length";
402 case SW_CHV_WRONG : return "CHV wrong";
403 case SW_CHV_BLOCKED : return "CHV blocked";
404 case SW_USE_CONDITIONS : return "use conditions not satisfied";
405 case SW_BAD_PARAMETER : return "bad parameter";
406 case SW_NOT_SUPPORTED : return "not supported";
407 case SW_FILE_NOT_FOUND : return "file not found";
408 case SW_RECORD_NOT_FOUND:return "record not found";
409 case SW_REF_NOT_FOUND : return "reference not found";
410 case SW_BAD_P0_P1 : return "bad P0 or P1";
411 case SW_INS_NOT_SUP : return "instruction not supported";
412 case SW_CLA_NOT_SUP : return "class not supported";
413 case SW_SUCCESS : return "success";
414 default:
415 if ((rc & ~0x00ff) == SW_MORE_DATA)
416 return "more data available";
417 if ( (rc & 0x10000) )
418 return host_sw_string (rc);
419 return "unknown status error";
426 ct API Interface
429 static const char *
430 ct_error_string (long err)
432 switch (err)
434 case 0: return "okay";
435 case -1: return "invalid data";
436 case -8: return "ct error";
437 case -10: return "transmission error";
438 case -11: return "memory allocation error";
439 case -128: return "HTSI error";
440 default: return "unknown CT-API error";
445 static void
446 ct_dump_reader_status (int slot)
448 log_info ("reader slot %d: %s\n", slot,
449 reader_table[slot].status == 1? "Processor ICC present" :
450 reader_table[slot].status == 0? "Memory ICC present" :
451 "ICC not present" );
455 /* Wait for the card in SLOT and activate it. Return a status word
456 error or 0 on success. */
457 static int
458 ct_activate_card (int slot)
460 int rc;
461 unsigned char dad[1], sad[1], cmd[11], buf[256];
462 unsigned short buflen;
464 /* Check whether card has been inserted. */
465 dad[0] = 1; /* Destination address: CT. */
466 sad[0] = 2; /* Source address: Host. */
468 cmd[0] = 0x20; /* Class byte. */
469 cmd[1] = 0x13; /* Request status. */
470 cmd[2] = 0x00; /* From kernel. */
471 cmd[3] = 0x80; /* Return card's DO. */
472 cmd[4] = 0x00;
474 buflen = DIM(buf);
476 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
477 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
479 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
480 slot, ct_error_string (rc));
481 return SW_HOST_CARD_IO_ERROR;
484 /* Connected, now activate the card. */
485 dad[0] = 1; /* Destination address: CT. */
486 sad[0] = 2; /* Source address: Host. */
488 cmd[0] = 0x20; /* Class byte. */
489 cmd[1] = 0x12; /* Request ICC. */
490 cmd[2] = 0x01; /* From first interface. */
491 cmd[3] = 0x01; /* Return card's ATR. */
492 cmd[4] = 0x00;
494 buflen = DIM(buf);
496 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
497 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
499 log_error ("ct_activate_card(%d): activation failed: %s\n",
500 slot, ct_error_string (rc));
501 if (!rc)
502 log_printhex (" received data:", buf, buflen);
503 return SW_HOST_CARD_IO_ERROR;
506 /* Store the type and the ATR. */
507 if (buflen - 2 > DIM (reader_table[0].atr))
509 log_error ("ct_activate_card(%d): ATR too long\n", slot);
510 return SW_HOST_CARD_IO_ERROR;
513 reader_table[slot].status = buf[buflen - 1];
514 memcpy (reader_table[slot].atr, buf, buflen - 2);
515 reader_table[slot].atrlen = buflen - 2;
516 return 0;
520 static int
521 close_ct_reader (int slot)
523 CT_close (slot);
524 reader_table[slot].used = 0;
525 return 0;
528 static int
529 reset_ct_reader (int slot)
531 /* FIXME: Check is this is sufficient do do a reset. */
532 return ct_activate_card (slot);
536 static int
537 ct_get_status (int slot, unsigned int *status)
539 *status = 1|2|4; /* FIXME */
540 return 0;
542 return SW_HOST_NOT_SUPPORTED;
545 /* Actually send the APDU of length APDULEN to SLOT and return a
546 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
547 set to BUFLEN. Returns: CT API error code. */
548 static int
549 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
550 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
552 int rc;
553 unsigned char dad[1], sad[1];
554 unsigned short ctbuflen;
556 /* If we don't have an ATR, we need to reset the reader first. */
557 if (!reader_table[slot].atrlen
558 && (rc = reset_ct_reader (slot)))
559 return rc;
561 dad[0] = 0; /* Destination address: Card. */
562 sad[0] = 2; /* Source address: Host. */
563 ctbuflen = *buflen;
564 if (DBG_CARD_IO)
565 log_printhex (" CT_data:", apdu, apdulen);
566 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
567 *buflen = ctbuflen;
569 return rc? SW_HOST_CARD_IO_ERROR: 0;
574 /* Open a reader and return an internal handle for it. PORT is a
575 non-negative value with the port number of the reader. USB readers
576 do have port numbers starting at 32769. */
577 static int
578 open_ct_reader (int port)
580 int rc, reader;
582 if (port < 0 || port > 0xffff)
584 log_error ("open_ct_reader: invalid port %d requested\n", port);
585 return -1;
587 reader = new_reader_slot ();
588 if (reader == -1)
589 return reader;
590 reader_table[reader].port = port;
592 rc = CT_init (reader, (unsigned short)port);
593 if (rc)
595 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
596 port, ct_error_string (rc));
597 reader_table[reader].used = 0;
598 return -1;
601 /* Only try to activate the card. */
602 rc = ct_activate_card (reader);
603 if (rc)
605 reader_table[reader].atrlen = 0;
606 rc = 0;
609 reader_table[reader].close_reader = close_ct_reader;
610 reader_table[reader].reset_reader = reset_ct_reader;
611 reader_table[reader].get_status_reader = ct_get_status;
612 reader_table[reader].send_apdu_reader = ct_send_apdu;
613 reader_table[reader].check_keypad = NULL;
614 reader_table[reader].dump_status_reader = ct_dump_reader_status;
616 dump_reader_status (reader);
617 return reader;
622 PC/SC Interface
625 #ifdef NEED_PCSC_WRAPPER
626 static int
627 writen (int fd, const void *buf, size_t nbytes)
629 size_t nleft = nbytes;
630 int nwritten;
632 /* log_printhex (" writen:", buf, nbytes); */
634 while (nleft > 0)
636 #ifdef USE_GNU_PTH
637 nwritten = pth_write (fd, buf, nleft);
638 #else
639 nwritten = write (fd, buf, nleft);
640 #endif
641 if (nwritten < 0 && errno == EINTR)
642 continue;
643 if (nwritten < 0)
644 return -1;
645 nleft -= nwritten;
646 buf = (const char*)buf + nwritten;
648 return 0;
651 /* Read up to BUFLEN bytes from FD and return the number of bytes
652 actually read in NREAD. Returns -1 on error or 0 on success. */
653 static int
654 readn (int fd, void *buf, size_t buflen, size_t *nread)
656 size_t nleft = buflen;
657 int n;
658 /* void *orig_buf = buf; */
660 while (nleft > 0)
662 #ifdef USE_GNU_PTH
663 n = pth_read (fd, buf, nleft);
664 #else
665 n = read (fd, buf, nleft);
666 #endif
667 if (n < 0 && errno == EINTR)
668 continue;
669 if (n < 0)
670 return -1; /* read error. */
671 if (!n)
672 break; /* EOF */
673 nleft -= n;
674 buf = (char*)buf + n;
676 if (nread)
677 *nread = buflen - nleft;
679 /* log_printhex (" readn:", orig_buf, *nread); */
681 return 0;
683 #endif /*NEED_PCSC_WRAPPER*/
685 static const char *
686 pcsc_error_string (long err)
688 const char *s;
690 if (!err)
691 return "okay";
692 if ((err & 0x80100000) != 0x80100000)
693 return "invalid PC/SC error code";
694 err &= 0xffff;
695 switch (err)
697 case 0x0002: s = "cancelled"; break;
698 case 0x000e: s = "can't dispose"; break;
699 case 0x0008: s = "insufficient buffer"; break;
700 case 0x0015: s = "invalid ATR"; break;
701 case 0x0003: s = "invalid handle"; break;
702 case 0x0004: s = "invalid parameter"; break;
703 case 0x0005: s = "invalid target"; break;
704 case 0x0011: s = "invalid value"; break;
705 case 0x0006: s = "no memory"; break;
706 case 0x0013: s = "comm error"; break;
707 case 0x0001: s = "internal error"; break;
708 case 0x0014: s = "unknown error"; break;
709 case 0x0007: s = "waited too long"; break;
710 case 0x0009: s = "unknown reader"; break;
711 case 0x000a: s = "timeout"; break;
712 case 0x000b: s = "sharing violation"; break;
713 case 0x000c: s = "no smartcard"; break;
714 case 0x000d: s = "unknown card"; break;
715 case 0x000f: s = "proto mismatch"; break;
716 case 0x0010: s = "not ready"; break;
717 case 0x0012: s = "system cancelled"; break;
718 case 0x0016: s = "not transacted"; break;
719 case 0x0017: s = "reader unavailable"; break;
720 case 0x0065: s = "unsupported card"; break;
721 case 0x0066: s = "unresponsive card"; break;
722 case 0x0067: s = "unpowered card"; break;
723 case 0x0068: s = "reset card"; break;
724 case 0x0069: s = "removed card"; break;
725 case 0x006a: s = "inserted card"; break;
726 case 0x001f: s = "unsupported feature"; break;
727 case 0x0019: s = "PCI too small"; break;
728 case 0x001a: s = "reader unsupported"; break;
729 case 0x001b: s = "duplicate reader"; break;
730 case 0x001c: s = "card unsupported"; break;
731 case 0x001d: s = "no service"; break;
732 case 0x001e: s = "service stopped"; break;
733 default: s = "unknown PC/SC error code"; break;
735 return s;
738 /* Map PC/SC error codes to our special host status words. */
739 static int
740 pcsc_error_to_sw (long ec)
742 int rc;
744 switch ( PCSC_ERR_MASK (ec) )
746 case 0: rc = 0; break;
748 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
749 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
750 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
751 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
752 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
753 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
755 case PCSC_E_INVALID_TARGET:
756 case PCSC_E_INVALID_VALUE:
757 case PCSC_E_INVALID_HANDLE:
758 case PCSC_E_INVALID_PARAMETER:
759 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
761 default: rc = SW_HOST_GENERAL_ERROR; break;
764 return rc;
767 static void
768 dump_pcsc_reader_status (int slot)
770 log_info ("reader slot %d: active protocol:", slot);
771 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
772 log_printf (" T0");
773 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
774 log_printf (" T1");
775 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
776 log_printf (" raw");
777 log_printf ("\n");
781 /* Send an PC/SC reset command and return a status word on error or 0
782 on success. */
783 static int
784 reset_pcsc_reader (int slot)
786 #ifdef NEED_PCSC_WRAPPER
787 long err;
788 reader_table_t slotp;
789 size_t len;
790 int i, n;
791 unsigned char msgbuf[9];
792 unsigned int dummy_status;
793 int sw = SW_HOST_CARD_IO_ERROR;
795 slotp = reader_table + slot;
797 if (slotp->pcsc.req_fd == -1
798 || slotp->pcsc.rsp_fd == -1
799 || slotp->pcsc.pid == (pid_t)(-1) )
801 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
802 return sw;
805 msgbuf[0] = 0x05; /* RESET command. */
806 len = 0;
807 msgbuf[1] = (len >> 24);
808 msgbuf[2] = (len >> 16);
809 msgbuf[3] = (len >> 8);
810 msgbuf[4] = (len );
811 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
813 log_error ("error sending PC/SC RESET request: %s\n",
814 strerror (errno));
815 goto command_failed;
818 /* Read the response. */
819 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
821 log_error ("error receiving PC/SC RESET response: %s\n",
822 i? strerror (errno) : "premature EOF");
823 goto command_failed;
825 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
826 if (msgbuf[0] != 0x81 || len < 4)
828 log_error ("invalid response header from PC/SC received\n");
829 goto command_failed;
831 len -= 4; /* Already read the error code. */
832 if (len > DIM (slotp->atr))
834 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
835 (unsigned long)len);
836 sw = SW_HOST_GENERAL_ERROR;
837 goto command_failed;
839 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
840 | (msgbuf[7] << 8 ) | msgbuf[8]);
841 if (err)
843 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
844 pcsc_error_string (err), err);
845 /* If the error code is no smart card, we should not considere
846 this a major error and close the wrapper. */
847 sw = pcsc_error_to_sw (err);
848 if (err == PCSC_E_NO_SMARTCARD)
849 return sw;
850 goto command_failed;
853 /* The open function may return a zero for the ATR length to
854 indicate that no card is present. */
855 n = len;
856 if (n)
858 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
860 log_error ("error receiving PC/SC RESET response: %s\n",
861 i? strerror (errno) : "premature EOF");
862 goto command_failed;
865 slotp->atrlen = len;
867 /* Read the status so that IS_T0 will be set. */
868 pcsc_get_status (slot, &dummy_status);
870 return 0;
872 command_failed:
873 close (slotp->pcsc.req_fd);
874 close (slotp->pcsc.rsp_fd);
875 slotp->pcsc.req_fd = -1;
876 slotp->pcsc.rsp_fd = -1;
877 kill (slotp->pcsc.pid, SIGTERM);
878 slotp->pcsc.pid = (pid_t)(-1);
879 slotp->used = 0;
880 return sw;
882 #else /* !NEED_PCSC_WRAPPER */
883 long err;
884 char reader[250];
885 unsigned long nreader, atrlen;
886 unsigned long card_state, card_protocol;
888 if (reader_table[slot].pcsc.card)
890 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
891 if (err)
893 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
894 pcsc_error_string (err), err);
895 return SW_HOST_CARD_IO_ERROR;
897 reader_table[slot].pcsc.card = 0;
900 err = pcsc_connect (reader_table[slot].pcsc.context,
901 reader_table[slot].rdrname,
902 PCSC_SHARE_EXCLUSIVE,
903 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
904 &reader_table[slot].pcsc.card,
905 &reader_table[slot].pcsc.protocol);
906 if (err)
908 log_error ("pcsc_connect failed: %s (0x%lx)\n",
909 pcsc_error_string (err), err);
910 reader_table[slot].pcsc.card = 0;
911 return pcsc_error_to_sw (err);
915 atrlen = 33;
916 nreader = sizeof reader - 1;
917 err = pcsc_status (reader_table[slot].pcsc.card,
918 reader, &nreader,
919 &card_state, &card_protocol,
920 reader_table[slot].atr, &atrlen);
921 if (err)
923 log_error ("pcsc_status failed: %s (0x%lx)\n",
924 pcsc_error_string (err), err);
925 reader_table[slot].atrlen = 0;
926 return pcsc_error_to_sw (err);
928 if (atrlen >= DIM (reader_table[0].atr))
929 log_bug ("ATR returned by pcsc_status is too large\n");
930 reader_table[slot].atrlen = atrlen;
931 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
933 return 0;
934 #endif /* !NEED_PCSC_WRAPPER */
938 static int
939 pcsc_get_status (int slot, unsigned int *status)
941 #ifdef NEED_PCSC_WRAPPER
942 long err;
943 reader_table_t slotp;
944 size_t len, full_len;
945 int i, n;
946 unsigned char msgbuf[9];
947 unsigned char buffer[16];
948 int sw = SW_HOST_CARD_IO_ERROR;
950 slotp = reader_table + slot;
952 if (slotp->pcsc.req_fd == -1
953 || slotp->pcsc.rsp_fd == -1
954 || slotp->pcsc.pid == (pid_t)(-1) )
956 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
957 return sw;
960 msgbuf[0] = 0x04; /* STATUS command. */
961 len = 0;
962 msgbuf[1] = (len >> 24);
963 msgbuf[2] = (len >> 16);
964 msgbuf[3] = (len >> 8);
965 msgbuf[4] = (len );
966 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
968 log_error ("error sending PC/SC STATUS request: %s\n",
969 strerror (errno));
970 goto command_failed;
973 /* Read the response. */
974 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
976 log_error ("error receiving PC/SC STATUS response: %s\n",
977 i? strerror (errno) : "premature EOF");
978 goto command_failed;
980 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
981 if (msgbuf[0] != 0x81 || len < 4)
983 log_error ("invalid response header from PC/SC received\n");
984 goto command_failed;
986 len -= 4; /* Already read the error code. */
987 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
988 | (msgbuf[7] << 8 ) | msgbuf[8]);
989 if (err)
991 log_error ("pcsc_status failed: %s (0x%lx)\n",
992 pcsc_error_string (err), err);
993 /* This is a proper error code, so return immediately. */
994 return pcsc_error_to_sw (err);
997 full_len = len;
999 /* The current version returns 3 words but we allow also for old
1000 versions returning only 2 words. */
1001 n = 12 < len ? 12 : len;
1002 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
1003 || (len != 8 && len != 12))
1005 log_error ("error receiving PC/SC STATUS response: %s\n",
1006 i? strerror (errno) : "premature EOF");
1007 goto command_failed;
1010 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
1013 full_len -= len;
1014 /* Newer versions of the wrapper might send more status bytes.
1015 Read them. */
1016 while (full_len)
1018 unsigned char dummybuf[128];
1020 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1021 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1023 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1024 i? strerror (errno) : "premature EOF");
1025 goto command_failed;
1027 full_len -= n;
1030 /* We are lucky: The wrapper already returns the data in the
1031 required format. */
1032 *status = buffer[3];
1034 return 0;
1036 command_failed:
1037 close (slotp->pcsc.req_fd);
1038 close (slotp->pcsc.rsp_fd);
1039 slotp->pcsc.req_fd = -1;
1040 slotp->pcsc.rsp_fd = -1;
1041 kill (slotp->pcsc.pid, SIGTERM);
1042 slotp->pcsc.pid = (pid_t)(-1);
1043 slotp->used = 0;
1044 return sw;
1046 #else /*!NEED_PCSC_WRAPPER*/
1048 long err;
1049 struct pcsc_readerstate_s rdrstates[1];
1051 memset (rdrstates, 0, sizeof *rdrstates);
1052 rdrstates[0].reader = reader_table[slot].rdrname;
1053 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
1054 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
1056 rdrstates, 1);
1057 if (err == PCSC_E_TIMEOUT)
1058 err = 0; /* Timeout is no error error here. */
1059 if (err)
1061 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
1062 pcsc_error_string (err), err);
1063 return pcsc_error_to_sw (err);
1067 /* log_debug */
1068 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
1069 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
1070 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
1071 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
1072 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
1073 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
1074 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
1075 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
1076 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
1077 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
1078 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
1080 *status = 0;
1081 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
1082 *status |= 2;
1083 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
1084 *status |= 4;
1085 /* We indicate a useful card if it is not in use by another
1086 application. This is because we only use exclusive access
1087 mode. */
1088 if ( (*status & 6) == 6
1089 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
1090 *status |= 1;
1092 return 0;
1093 #endif /*!NEED_PCSC_WRAPPER*/
1097 /* Actually send the APDU of length APDULEN to SLOT and return a
1098 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1099 set to BUFLEN. Returns: CT API error code. */
1100 static int
1101 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1102 unsigned char *buffer, size_t *buflen,
1103 struct pininfo_s *pininfo)
1105 #ifdef NEED_PCSC_WRAPPER
1106 long err;
1107 reader_table_t slotp;
1108 size_t len, full_len;
1109 int i, n;
1110 unsigned char msgbuf[9];
1111 int sw = SW_HOST_CARD_IO_ERROR;
1113 if (!reader_table[slot].atrlen
1114 && (err = reset_pcsc_reader (slot)))
1115 return err;
1117 if (DBG_CARD_IO)
1118 log_printhex (" PCSC_data:", apdu, apdulen);
1120 slotp = reader_table + slot;
1122 if (slotp->pcsc.req_fd == -1
1123 || slotp->pcsc.rsp_fd == -1
1124 || slotp->pcsc.pid == (pid_t)(-1) )
1126 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1127 return sw;
1130 msgbuf[0] = 0x03; /* TRANSMIT command. */
1131 len = apdulen;
1132 msgbuf[1] = (len >> 24);
1133 msgbuf[2] = (len >> 16);
1134 msgbuf[3] = (len >> 8);
1135 msgbuf[4] = (len );
1136 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1137 || writen (slotp->pcsc.req_fd, apdu, len))
1139 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1140 strerror (errno));
1141 goto command_failed;
1144 /* Read the response. */
1145 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1147 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1148 i? strerror (errno) : "premature EOF");
1149 goto command_failed;
1151 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1152 if (msgbuf[0] != 0x81 || len < 4)
1154 log_error ("invalid response header from PC/SC received\n");
1155 goto command_failed;
1157 len -= 4; /* Already read the error code. */
1158 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1159 | (msgbuf[7] << 8 ) | msgbuf[8]);
1160 if (err)
1162 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1163 pcsc_error_string (err), err);
1164 return pcsc_error_to_sw (err);
1167 full_len = len;
1169 n = *buflen < len ? *buflen : len;
1170 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1172 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1173 i? strerror (errno) : "premature EOF");
1174 goto command_failed;
1176 *buflen = n;
1178 full_len -= len;
1179 if (full_len)
1181 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1182 err = SW_HOST_INV_VALUE;
1184 /* We need to read any rest of the response, to keep the
1185 protocol runnng. */
1186 while (full_len)
1188 unsigned char dummybuf[128];
1190 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1191 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1193 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1194 i? strerror (errno) : "premature EOF");
1195 goto command_failed;
1197 full_len -= n;
1200 return err;
1202 command_failed:
1203 close (slotp->pcsc.req_fd);
1204 close (slotp->pcsc.rsp_fd);
1205 slotp->pcsc.req_fd = -1;
1206 slotp->pcsc.rsp_fd = -1;
1207 kill (slotp->pcsc.pid, SIGTERM);
1208 slotp->pcsc.pid = (pid_t)(-1);
1209 slotp->used = 0;
1210 return sw;
1212 #else /*!NEED_PCSC_WRAPPER*/
1214 long err;
1215 struct pcsc_io_request_s send_pci;
1216 unsigned long recv_len;
1218 if (!reader_table[slot].atrlen
1219 && (err = reset_pcsc_reader (slot)))
1220 return err;
1222 if (DBG_CARD_IO)
1223 log_printhex (" PCSC_data:", apdu, apdulen);
1225 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1226 send_pci.protocol = PCSC_PROTOCOL_T1;
1227 else
1228 send_pci.protocol = PCSC_PROTOCOL_T0;
1229 send_pci.pci_len = sizeof send_pci;
1230 recv_len = *buflen;
1231 err = pcsc_transmit (reader_table[slot].pcsc.card,
1232 &send_pci, apdu, apdulen,
1233 NULL, buffer, &recv_len);
1234 *buflen = recv_len;
1235 if (err)
1236 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1237 pcsc_error_string (err), err);
1239 return pcsc_error_to_sw (err);
1240 #endif /*!NEED_PCSC_WRAPPER*/
1244 static int
1245 close_pcsc_reader (int slot)
1247 #ifdef NEED_PCSC_WRAPPER
1248 long err;
1249 reader_table_t slotp;
1250 size_t len;
1251 int i;
1252 unsigned char msgbuf[9];
1254 slotp = reader_table + slot;
1256 if (slotp->pcsc.req_fd == -1
1257 || slotp->pcsc.rsp_fd == -1
1258 || slotp->pcsc.pid == (pid_t)(-1) )
1260 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1261 return 0;
1264 msgbuf[0] = 0x02; /* CLOSE command. */
1265 len = 0;
1266 msgbuf[1] = (len >> 24);
1267 msgbuf[2] = (len >> 16);
1268 msgbuf[3] = (len >> 8);
1269 msgbuf[4] = (len );
1270 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1272 log_error ("error sending PC/SC CLOSE request: %s\n",
1273 strerror (errno));
1274 goto command_failed;
1277 /* Read the response. */
1278 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1280 log_error ("error receiving PC/SC CLOSE response: %s\n",
1281 i? strerror (errno) : "premature EOF");
1282 goto command_failed;
1284 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1285 if (msgbuf[0] != 0x81 || len < 4)
1287 log_error ("invalid response header from PC/SC received\n");
1288 goto command_failed;
1290 len -= 4; /* Already read the error code. */
1291 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1292 | (msgbuf[7] << 8 ) | msgbuf[8]);
1293 if (err)
1294 log_error ("pcsc_close failed: %s (0x%lx)\n",
1295 pcsc_error_string (err), err);
1297 /* We will close the wrapper in any case - errors are merely
1298 informational. */
1300 command_failed:
1301 close (slotp->pcsc.req_fd);
1302 close (slotp->pcsc.rsp_fd);
1303 slotp->pcsc.req_fd = -1;
1304 slotp->pcsc.rsp_fd = -1;
1305 kill (slotp->pcsc.pid, SIGTERM);
1306 slotp->pcsc.pid = (pid_t)(-1);
1307 slotp->used = 0;
1308 return 0;
1310 #else /*!NEED_PCSC_WRAPPER*/
1312 pcsc_release_context (reader_table[slot].pcsc.context);
1313 xfree (reader_table[slot].rdrname);
1314 reader_table[slot].rdrname = NULL;
1315 reader_table[slot].used = 0;
1316 return 0;
1317 #endif /*!NEED_PCSC_WRAPPER*/
1320 /* Note: It is a pitty that we can't return proper error codes. */
1321 static int
1322 open_pcsc_reader (const char *portstr)
1324 #ifdef NEED_PCSC_WRAPPER
1325 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1326 needed to cope with different thread models and other peculiarities
1327 of libpcsclite. */
1328 int slot;
1329 reader_table_t slotp;
1330 int fd, rp[2], wp[2];
1331 int n, i;
1332 pid_t pid;
1333 size_t len;
1334 unsigned char msgbuf[9];
1335 int err;
1336 unsigned int dummy_status;
1337 int sw = SW_HOST_CARD_IO_ERROR;
1338 /* Note that we use the constant and not the fucntion because this
1339 code won't be be used under Windows. */
1340 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1342 if (access (wrapperpgm, X_OK))
1344 log_error ("can't run PC/SC access module `%s': %s\n",
1345 wrapperpgm, strerror (errno));
1346 return -1;
1349 slot = new_reader_slot ();
1350 if (slot == -1)
1351 return -1;
1352 slotp = reader_table + slot;
1354 /* Fire up the pcsc wrapper. We don't use any fork/exec code from
1355 the common directy but implement it direclty so that this file
1356 may still be source copied. */
1358 if (pipe (rp) == -1)
1360 log_error ("error creating a pipe: %s\n", strerror (errno));
1361 slotp->used = 0;
1362 return -1;
1364 if (pipe (wp) == -1)
1366 log_error ("error creating a pipe: %s\n", strerror (errno));
1367 close (rp[0]);
1368 close (rp[1]);
1369 slotp->used = 0;
1370 return -1;
1373 pid = fork ();
1374 if (pid == -1)
1376 log_error ("error forking process: %s\n", strerror (errno));
1377 close (rp[0]);
1378 close (rp[1]);
1379 close (wp[0]);
1380 close (wp[1]);
1381 slotp->used = 0;
1382 return -1;
1384 slotp->pcsc.pid = pid;
1386 if (!pid)
1387 { /*
1388 === Child ===
1391 /* Double fork. */
1392 pid = fork ();
1393 if (pid == -1)
1394 _exit (31);
1395 if (pid)
1396 _exit (0); /* Immediate exit this parent, so that the child
1397 gets cleaned up by the init process. */
1399 /* Connect our pipes. */
1400 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1401 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1402 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1403 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1405 /* Send stderr to the bit bucket. */
1406 fd = open ("/dev/null", O_WRONLY);
1407 if (fd == -1)
1408 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1409 if (fd != 2 && dup2 (fd, 2) == -1)
1410 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1412 /* Close all other files. */
1413 n = sysconf (_SC_OPEN_MAX);
1414 if (n < 0)
1415 n = MAX_OPEN_FDS;
1416 for (i=3; i < n; i++)
1417 close(i);
1418 errno = 0;
1420 execl (wrapperpgm,
1421 "pcsc-wrapper",
1422 "--",
1423 "1", /* API version */
1424 opt.pcsc_driver, /* Name of the PC/SC library. */
1425 NULL);
1426 _exit (31);
1430 === Parent ===
1432 close (wp[0]);
1433 close (rp[1]);
1434 slotp->pcsc.req_fd = wp[1];
1435 slotp->pcsc.rsp_fd = rp[0];
1437 /* Wait for the intermediate child to terminate. */
1438 #ifdef USE_GNU_PTH
1439 #define WAIT pth_waitpid
1440 #else
1441 #define WAIT waitpid
1442 #endif
1443 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1445 #undef X
1447 /* Now send the open request. */
1448 msgbuf[0] = 0x01; /* OPEN command. */
1449 len = portstr? strlen (portstr):0;
1450 msgbuf[1] = (len >> 24);
1451 msgbuf[2] = (len >> 16);
1452 msgbuf[3] = (len >> 8);
1453 msgbuf[4] = (len );
1454 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1455 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1457 log_error ("error sending PC/SC OPEN request: %s\n",
1458 strerror (errno));
1459 goto command_failed;
1461 /* Read the response. */
1462 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1464 log_error ("error receiving PC/SC OPEN response: %s\n",
1465 i? strerror (errno) : "premature EOF");
1466 goto command_failed;
1468 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1469 if (msgbuf[0] != 0x81 || len < 4)
1471 log_error ("invalid response header from PC/SC received\n");
1472 goto command_failed;
1474 len -= 4; /* Already read the error code. */
1475 if (len > DIM (slotp->atr))
1477 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1478 (unsigned long)len);
1479 goto command_failed;
1481 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1482 | (msgbuf[7] << 8 ) | msgbuf[8]);
1483 if (err)
1485 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1486 sw = pcsc_error_to_sw (err);
1487 goto command_failed;
1490 slotp->last_status = 0;
1492 /* The open request may return a zero for the ATR length to
1493 indicate that no card is present. */
1494 n = len;
1495 if (n)
1497 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1499 log_error ("error receiving PC/SC OPEN response: %s\n",
1500 i? strerror (errno) : "premature EOF");
1501 goto command_failed;
1503 /* If we got to here we know that a card is present
1504 and usable. Thus remember this. */
1505 slotp->last_status = (1|2|4| 0x8000);
1507 slotp->atrlen = len;
1509 reader_table[slot].close_reader = close_pcsc_reader;
1510 reader_table[slot].reset_reader = reset_pcsc_reader;
1511 reader_table[slot].get_status_reader = pcsc_get_status;
1512 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1513 reader_table[slot].check_keypad = NULL;
1514 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1516 /* Read the status so that IS_T0 will be set. */
1517 pcsc_get_status (slot, &dummy_status);
1519 dump_reader_status (slot);
1520 return slot;
1522 command_failed:
1523 close (slotp->pcsc.req_fd);
1524 close (slotp->pcsc.rsp_fd);
1525 slotp->pcsc.req_fd = -1;
1526 slotp->pcsc.rsp_fd = -1;
1527 kill (slotp->pcsc.pid, SIGTERM);
1528 slotp->pcsc.pid = (pid_t)(-1);
1529 slotp->used = 0;
1530 /* There is no way to return SW. */
1531 return -1;
1533 #else /*!NEED_PCSC_WRAPPER */
1534 long err;
1535 int slot;
1536 char *list = NULL;
1537 unsigned long nreader, listlen, atrlen;
1538 char *p;
1539 unsigned long card_state, card_protocol;
1541 slot = new_reader_slot ();
1542 if (slot == -1)
1543 return -1;
1545 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1546 &reader_table[slot].pcsc.context);
1547 if (err)
1549 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1550 pcsc_error_string (err), err);
1551 reader_table[slot].used = 0;
1552 return -1;
1555 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1556 NULL, NULL, &nreader);
1557 if (!err)
1559 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1560 if (!list)
1562 log_error ("error allocating memory for reader list\n");
1563 pcsc_release_context (reader_table[slot].pcsc.context);
1564 reader_table[slot].used = 0;
1565 return -1 /*SW_HOST_OUT_OF_CORE*/;
1567 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1568 NULL, list, &nreader);
1570 if (err)
1572 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1573 pcsc_error_string (err), err);
1574 pcsc_release_context (reader_table[slot].pcsc.context);
1575 reader_table[slot].used = 0;
1576 xfree (list);
1577 return -1 /*pcsc_error_to_sw (err)*/;
1580 listlen = nreader;
1581 p = list;
1582 while (nreader)
1584 if (!*p && !p[1])
1585 break;
1586 if (*p)
1587 log_info ("detected reader `%s'\n", p);
1588 if (nreader < (strlen (p)+1))
1590 log_error ("invalid response from pcsc_list_readers\n");
1591 break;
1593 nreader -= strlen (p)+1;
1594 p += strlen (p) + 1;
1597 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1598 if (!reader_table[slot].rdrname)
1600 log_error ("error allocating memory for reader name\n");
1601 pcsc_release_context (reader_table[slot].pcsc.context);
1602 reader_table[slot].used = 0;
1603 return -1 /*SW_HOST_OUT_OF_CORE*/;
1605 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1606 xfree (list);
1607 list = NULL;
1609 err = pcsc_connect (reader_table[slot].pcsc.context,
1610 reader_table[slot].rdrname,
1611 PCSC_SHARE_EXCLUSIVE,
1612 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1613 &reader_table[slot].pcsc.card,
1614 &reader_table[slot].pcsc.protocol);
1615 if (err == PCSC_E_NO_SMARTCARD)
1616 reader_table[slot].pcsc.card = 0;
1617 else if (err)
1619 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1620 pcsc_error_string (err), err);
1621 pcsc_release_context (reader_table[slot].pcsc.context);
1622 xfree (reader_table[slot].rdrname);
1623 reader_table[slot].rdrname = NULL;
1624 reader_table[slot].used = 0;
1625 return -1 /*pcsc_error_to_sw (err)*/;
1628 reader_table[slot].atrlen = 0;
1629 reader_table[slot].last_status = 0;
1630 if (!err)
1632 char reader[250];
1633 unsigned long readerlen;
1635 atrlen = 32;
1636 readerlen = sizeof reader -1 ;
1637 err = pcsc_status (reader_table[slot].pcsc.card,
1638 reader, &readerlen,
1639 &card_state, &card_protocol,
1640 reader_table[slot].atr, &atrlen);
1641 if (err)
1642 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1643 pcsc_error_string (err), err, readerlen);
1644 else
1646 if (atrlen >= DIM (reader_table[0].atr))
1647 log_bug ("ATR returned by pcsc_status is too large\n");
1648 reader_table[slot].atrlen = atrlen;
1649 /* If we got to here we know that a card is present
1650 and usable. Thus remember this. */
1651 reader_table[slot].last_status = (1|2|4| 0x8000);
1652 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1656 reader_table[slot].close_reader = close_pcsc_reader;
1657 reader_table[slot].reset_reader = reset_pcsc_reader;
1658 reader_table[slot].get_status_reader = pcsc_get_status;
1659 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1660 reader_table[slot].check_keypad = NULL;
1661 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1663 /* log_debug ("state from pcsc_status: 0x%lx\n", card_state); */
1664 /* log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
1666 dump_reader_status (slot);
1667 return slot;
1668 #endif /*!NEED_PCSC_WRAPPER */
1674 #ifdef HAVE_LIBUSB
1676 Internal CCID driver interface.
1680 static void
1681 dump_ccid_reader_status (int slot)
1683 log_info ("reader slot %d: using ccid driver\n", slot);
1686 static int
1687 close_ccid_reader (int slot)
1689 ccid_close_reader (reader_table[slot].ccid.handle);
1690 reader_table[slot].used = 0;
1691 return 0;
1695 static int
1696 shutdown_ccid_reader (int slot)
1698 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1699 return 0;
1703 static int
1704 reset_ccid_reader (int slot)
1706 int err;
1707 reader_table_t slotp = reader_table + slot;
1708 unsigned char atr[33];
1709 size_t atrlen;
1711 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1712 if (err)
1713 return err;
1714 /* If the reset was successful, update the ATR. */
1715 assert (sizeof slotp->atr >= sizeof atr);
1716 slotp->atrlen = atrlen;
1717 memcpy (slotp->atr, atr, atrlen);
1718 dump_reader_status (slot);
1719 return 0;
1723 static int
1724 get_status_ccid (int slot, unsigned int *status)
1726 int rc;
1727 int bits;
1729 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1730 if (rc)
1731 return -1;
1733 if (bits == 0)
1734 *status = 1|2|4;
1735 else if (bits == 1)
1736 *status = 2;
1737 else
1738 *status = 0;
1740 return 0;
1744 /* Actually send the APDU of length APDULEN to SLOT and return a
1745 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1746 set to BUFLEN. Returns: Internal CCID driver error code. */
1747 static int
1748 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1749 unsigned char *buffer, size_t *buflen,
1750 struct pininfo_s *pininfo)
1752 long err;
1753 size_t maxbuflen;
1755 /* If we don't have an ATR, we need to reset the reader first. */
1756 if (!reader_table[slot].atrlen
1757 && (err = reset_ccid_reader (slot)))
1758 return err;
1760 if (DBG_CARD_IO)
1761 log_printhex (" APDU_data:", apdu, apdulen);
1763 maxbuflen = *buflen;
1764 if (pininfo)
1765 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1766 apdu, apdulen,
1767 pininfo->mode,
1768 pininfo->minlen,
1769 pininfo->maxlen,
1770 pininfo->padlen,
1771 buffer, maxbuflen, buflen);
1772 else
1773 err = ccid_transceive (reader_table[slot].ccid.handle,
1774 apdu, apdulen,
1775 buffer, maxbuflen, buflen);
1776 if (err)
1777 log_error ("ccid_transceive failed: (0x%lx)\n",
1778 err);
1780 return err;
1784 /* Check whether the CCID reader supports the ISO command code COMMAND
1785 on the keypad. Return 0 on success. For a description of the pin
1786 parameters, see ccid-driver.c */
1787 static int
1788 check_ccid_keypad (int slot, int command, int pin_mode,
1789 int pinlen_min, int pinlen_max, int pin_padlen)
1791 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1793 apdu[1] = command;
1794 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1795 apdu, sizeof apdu,
1796 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1797 NULL, 0, NULL);
1801 /* Open the reader and try to read an ATR. */
1802 static int
1803 open_ccid_reader (const char *portstr)
1805 int err;
1806 int slot;
1807 reader_table_t slotp;
1809 slot = new_reader_slot ();
1810 if (slot == -1)
1811 return -1;
1812 slotp = reader_table + slot;
1814 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1815 if (err)
1817 slotp->used = 0;
1818 return -1;
1821 err = ccid_get_atr (slotp->ccid.handle,
1822 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1823 if (err)
1825 slotp->atrlen = 0;
1826 err = 0;
1828 else
1830 /* If we got to here we know that a card is present
1831 and usable. Thus remember this. */
1832 reader_table[slot].last_status = (1|2|4| 0x8000);
1835 reader_table[slot].close_reader = close_ccid_reader;
1836 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1837 reader_table[slot].reset_reader = reset_ccid_reader;
1838 reader_table[slot].get_status_reader = get_status_ccid;
1839 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1840 reader_table[slot].check_keypad = check_ccid_keypad;
1841 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1843 dump_reader_status (slot);
1844 return slot;
1849 #endif /* HAVE_LIBUSB */
1853 #ifdef USE_G10CODE_RAPDU
1855 The Remote APDU Interface.
1857 This uses the Remote APDU protocol to contact a reader.
1859 The port number is actually an index into the list of ports as
1860 returned via the protocol.
1864 static int
1865 rapdu_status_to_sw (int status)
1867 int rc;
1869 switch (status)
1871 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1873 case RAPDU_STATUS_INVCMD:
1874 case RAPDU_STATUS_INVPROT:
1875 case RAPDU_STATUS_INVSEQ:
1876 case RAPDU_STATUS_INVCOOKIE:
1877 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1879 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1880 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1881 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1882 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1883 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1884 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1886 default: rc = SW_HOST_GENERAL_ERROR; break;
1889 return rc;
1894 static int
1895 close_rapdu_reader (int slot)
1897 rapdu_release (reader_table[slot].rapdu.handle);
1898 reader_table[slot].used = 0;
1899 return 0;
1903 static int
1904 reset_rapdu_reader (int slot)
1906 int err;
1907 reader_table_t slotp;
1908 rapdu_msg_t msg = NULL;
1910 slotp = reader_table + slot;
1912 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1913 if (err)
1915 log_error ("sending rapdu command RESET failed: %s\n",
1916 err < 0 ? strerror (errno): rapdu_strerror (err));
1917 rapdu_msg_release (msg);
1918 return rapdu_status_to_sw (err);
1920 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1921 if (err)
1923 log_error ("receiving rapdu message failed: %s\n",
1924 err < 0 ? strerror (errno): rapdu_strerror (err));
1925 rapdu_msg_release (msg);
1926 return rapdu_status_to_sw (err);
1928 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1930 int sw = rapdu_status_to_sw (msg->cmd);
1931 log_error ("rapdu command RESET failed: %s\n",
1932 rapdu_strerror (msg->cmd));
1933 rapdu_msg_release (msg);
1934 return sw;
1936 if (msg->datalen >= DIM (slotp->atr))
1938 log_error ("ATR returned by the RAPDU layer is too large\n");
1939 rapdu_msg_release (msg);
1940 return SW_HOST_INV_VALUE;
1942 slotp->atrlen = msg->datalen;
1943 memcpy (slotp->atr, msg->data, msg->datalen);
1945 rapdu_msg_release (msg);
1946 return 0;
1950 static int
1951 my_rapdu_get_status (int slot, unsigned int *status)
1953 int err;
1954 reader_table_t slotp;
1955 rapdu_msg_t msg = NULL;
1956 int oldslot;
1958 slotp = reader_table + slot;
1960 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
1961 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
1962 rapdu_set_reader (slotp->rapdu.handle, oldslot);
1963 if (err)
1965 log_error ("sending rapdu command GET_STATUS failed: %s\n",
1966 err < 0 ? strerror (errno): rapdu_strerror (err));
1967 return rapdu_status_to_sw (err);
1969 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1970 if (err)
1972 log_error ("receiving rapdu message failed: %s\n",
1973 err < 0 ? strerror (errno): rapdu_strerror (err));
1974 rapdu_msg_release (msg);
1975 return rapdu_status_to_sw (err);
1977 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1979 int sw = rapdu_status_to_sw (msg->cmd);
1980 log_error ("rapdu command GET_STATUS failed: %s\n",
1981 rapdu_strerror (msg->cmd));
1982 rapdu_msg_release (msg);
1983 return sw;
1985 *status = msg->data[0];
1987 rapdu_msg_release (msg);
1988 return 0;
1992 /* Actually send the APDU of length APDULEN to SLOT and return a
1993 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1994 set to BUFLEN. Returns: APDU error code. */
1995 static int
1996 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1997 unsigned char *buffer, size_t *buflen,
1998 struct pininfo_s *pininfo)
2000 int err;
2001 reader_table_t slotp;
2002 rapdu_msg_t msg = NULL;
2003 size_t maxlen = *buflen;
2005 slotp = reader_table + slot;
2007 *buflen = 0;
2008 if (DBG_CARD_IO)
2009 log_printhex (" APDU_data:", apdu, apdulen);
2011 if (apdulen < 4)
2013 log_error ("rapdu_send_apdu: APDU is too short\n");
2014 return SW_HOST_INV_VALUE;
2017 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2018 if (err)
2020 log_error ("sending rapdu command APDU failed: %s\n",
2021 err < 0 ? strerror (errno): rapdu_strerror (err));
2022 rapdu_msg_release (msg);
2023 return rapdu_status_to_sw (err);
2025 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2026 if (err)
2028 log_error ("receiving rapdu message failed: %s\n",
2029 err < 0 ? strerror (errno): rapdu_strerror (err));
2030 rapdu_msg_release (msg);
2031 return rapdu_status_to_sw (err);
2033 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2035 int sw = rapdu_status_to_sw (msg->cmd);
2036 log_error ("rapdu command APDU failed: %s\n",
2037 rapdu_strerror (msg->cmd));
2038 rapdu_msg_release (msg);
2039 return sw;
2042 if (msg->datalen > maxlen)
2044 log_error ("rapdu response apdu too large\n");
2045 rapdu_msg_release (msg);
2046 return SW_HOST_INV_VALUE;
2049 *buflen = msg->datalen;
2050 memcpy (buffer, msg->data, msg->datalen);
2052 rapdu_msg_release (msg);
2053 return 0;
2056 static int
2057 open_rapdu_reader (int portno,
2058 const unsigned char *cookie, size_t length,
2059 int (*readfnc) (void *opaque,
2060 void *buffer, size_t size),
2061 void *readfnc_value,
2062 int (*writefnc) (void *opaque,
2063 const void *buffer, size_t size),
2064 void *writefnc_value,
2065 void (*closefnc) (void *opaque),
2066 void *closefnc_value)
2068 int err;
2069 int slot;
2070 reader_table_t slotp;
2071 rapdu_msg_t msg = NULL;
2073 slot = new_reader_slot ();
2074 if (slot == -1)
2075 return -1;
2076 slotp = reader_table + slot;
2078 slotp->rapdu.handle = rapdu_new ();
2079 if (!slotp->rapdu.handle)
2081 slotp->used = 0;
2082 return -1;
2085 rapdu_set_reader (slotp->rapdu.handle, portno);
2087 rapdu_set_iofunc (slotp->rapdu.handle,
2088 readfnc, readfnc_value,
2089 writefnc, writefnc_value,
2090 closefnc, closefnc_value);
2091 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2093 /* First try to get the current ATR, but if the card is inactive
2094 issue a reset instead. */
2095 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2096 if (err == RAPDU_STATUS_NEEDRESET)
2097 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2098 if (err)
2100 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2101 err < 0 ? strerror (errno): rapdu_strerror (err));
2102 goto failure;
2104 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2105 if (err)
2107 log_info ("receiving rapdu message failed: %s\n",
2108 err < 0 ? strerror (errno): rapdu_strerror (err));
2109 goto failure;
2111 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2113 log_info ("rapdu command GET ATR failed: %s\n",
2114 rapdu_strerror (msg->cmd));
2115 goto failure;
2117 if (msg->datalen >= DIM (slotp->atr))
2119 log_error ("ATR returned by the RAPDU layer is too large\n");
2120 goto failure;
2122 slotp->atrlen = msg->datalen;
2123 memcpy (slotp->atr, msg->data, msg->datalen);
2125 reader_table[slot].close_reader = close_rapdu_reader;
2126 reader_table[slot].reset_reader = reset_rapdu_reader;
2127 reader_table[slot].get_status_reader = my_rapdu_get_status;
2128 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2129 reader_table[slot].check_keypad = NULL;
2130 reader_table[slot].dump_status_reader = NULL;
2132 dump_reader_status (slot);
2133 rapdu_msg_release (msg);
2134 return slot;
2136 failure:
2137 rapdu_msg_release (msg);
2138 rapdu_release (slotp->rapdu.handle);
2139 slotp->used = 0;
2140 return -1;
2143 #endif /*USE_G10CODE_RAPDU*/
2148 Driver Access
2152 static int
2153 lock_slot (int slot)
2155 #ifdef USE_GNU_PTH
2156 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2158 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2159 return SW_HOST_LOCKING_FAILED;
2161 #endif /*USE_GNU_PTH*/
2162 return 0;
2165 static int
2166 trylock_slot (int slot)
2168 #ifdef USE_GNU_PTH
2169 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2171 if (errno == EBUSY)
2172 return SW_HOST_BUSY;
2173 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2174 return SW_HOST_LOCKING_FAILED;
2176 #endif /*USE_GNU_PTH*/
2177 return 0;
2180 static void
2181 unlock_slot (int slot)
2183 #ifdef USE_GNU_PTH
2184 if (!pth_mutex_release (&reader_table[slot].lock))
2185 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2186 #endif /*USE_GNU_PTH*/
2190 /* Open the reader and return an internal slot number or -1 on
2191 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2192 the first USB reader. For PC/SC the first listed reader). */
2194 apdu_open_reader (const char *portstr)
2196 static int pcsc_api_loaded, ct_api_loaded;
2198 #ifdef HAVE_LIBUSB
2199 if (!opt.disable_ccid)
2201 int slot, i;
2202 const char *s;
2204 slot = open_ccid_reader (portstr);
2205 if (slot != -1)
2206 return slot; /* got one */
2208 /* If a CCID reader specification has been given, the user does
2209 not want a fallback to other drivers. */
2210 if (portstr)
2211 for (s=portstr, i=0; *s; s++)
2212 if (*s == ':' && (++i == 3))
2213 return -1;
2216 #endif /* HAVE_LIBUSB */
2218 if (opt.ctapi_driver && *opt.ctapi_driver)
2220 int port = portstr? atoi (portstr) : 32768;
2222 if (!ct_api_loaded)
2224 void *handle;
2226 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2227 if (!handle)
2229 log_error ("apdu_open_reader: failed to open driver: %s\n",
2230 dlerror ());
2231 return -1;
2233 CT_init = dlsym (handle, "CT_init");
2234 CT_data = dlsym (handle, "CT_data");
2235 CT_close = dlsym (handle, "CT_close");
2236 if (!CT_init || !CT_data || !CT_close)
2238 log_error ("apdu_open_reader: invalid CT-API driver\n");
2239 dlclose (handle);
2240 return -1;
2242 ct_api_loaded = 1;
2244 return open_ct_reader (port);
2248 /* No ctAPI configured, so lets try the PC/SC API */
2249 if (!pcsc_api_loaded)
2251 #ifndef NEED_PCSC_WRAPPER
2252 void *handle;
2254 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2255 if (!handle)
2257 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2258 opt.pcsc_driver, dlerror ());
2259 return -1;
2262 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2263 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2264 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2265 #if defined(_WIN32) || defined(__CYGWIN__)
2266 if (!pcsc_list_readers)
2267 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2268 #endif
2269 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2270 #if defined(_WIN32) || defined(__CYGWIN__)
2271 if (!pcsc_get_status_change)
2272 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2273 #endif
2274 pcsc_connect = dlsym (handle, "SCardConnect");
2275 #if defined(_WIN32) || defined(__CYGWIN__)
2276 if (!pcsc_connect)
2277 pcsc_connect = dlsym (handle, "SCardConnectA");
2278 #endif
2279 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2280 #if defined(_WIN32) || defined(__CYGWIN__)
2281 if (!pcsc_reconnect)
2282 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2283 #endif
2284 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2285 pcsc_status = dlsym (handle, "SCardStatus");
2286 #if defined(_WIN32) || defined(__CYGWIN__)
2287 if (!pcsc_status)
2288 pcsc_status = dlsym (handle, "SCardStatusA");
2289 #endif
2290 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2291 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2292 pcsc_transmit = dlsym (handle, "SCardTransmit");
2293 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2295 if (!pcsc_establish_context
2296 || !pcsc_release_context
2297 || !pcsc_list_readers
2298 || !pcsc_get_status_change
2299 || !pcsc_connect
2300 || !pcsc_reconnect
2301 || !pcsc_disconnect
2302 || !pcsc_status
2303 || !pcsc_begin_transaction
2304 || !pcsc_end_transaction
2305 || !pcsc_transmit
2306 /* || !pcsc_set_timeout */)
2308 /* Note that set_timeout is currently not used and also not
2309 available under Windows. */
2310 log_error ("apdu_open_reader: invalid PC/SC driver "
2311 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2312 !!pcsc_establish_context,
2313 !!pcsc_release_context,
2314 !!pcsc_list_readers,
2315 !!pcsc_get_status_change,
2316 !!pcsc_connect,
2317 !!pcsc_reconnect,
2318 !!pcsc_disconnect,
2319 !!pcsc_status,
2320 !!pcsc_begin_transaction,
2321 !!pcsc_end_transaction,
2322 !!pcsc_transmit,
2323 !!pcsc_set_timeout );
2324 dlclose (handle);
2325 return -1;
2327 #endif /*!NEED_PCSC_WRAPPER*/
2328 pcsc_api_loaded = 1;
2331 return open_pcsc_reader (portstr);
2335 /* Open an remote reader and return an internal slot number or -1 on
2336 error. This function is an alternative to apdu_open_reader and used
2337 with remote readers only. Note that the supplied CLOSEFNC will
2338 only be called once and the slot will not be valid afther this.
2340 If PORTSTR is NULL we default to the first availabe port.
2343 apdu_open_remote_reader (const char *portstr,
2344 const unsigned char *cookie, size_t length,
2345 int (*readfnc) (void *opaque,
2346 void *buffer, size_t size),
2347 void *readfnc_value,
2348 int (*writefnc) (void *opaque,
2349 const void *buffer, size_t size),
2350 void *writefnc_value,
2351 void (*closefnc) (void *opaque),
2352 void *closefnc_value)
2354 #ifdef USE_G10CODE_RAPDU
2355 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2356 cookie, length,
2357 readfnc, readfnc_value,
2358 writefnc, writefnc_value,
2359 closefnc, closefnc_value);
2360 #else
2361 #ifdef _WIN32
2362 errno = ENOENT;
2363 #else
2364 errno = ENOSYS;
2365 #endif
2366 return -1;
2367 #endif
2372 apdu_close_reader (int slot)
2374 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2375 return SW_HOST_NO_DRIVER;
2376 if (reader_table[slot].close_reader)
2377 return reader_table[slot].close_reader (slot);
2378 return SW_HOST_NOT_SUPPORTED;
2381 /* Shutdown a reader; that is basically the same as a close but keeps
2382 the handle ready for later use. A apdu_reset_reader should be used
2383 to get it active again. */
2385 apdu_shutdown_reader (int slot)
2387 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2388 return SW_HOST_NO_DRIVER;
2389 if (reader_table[slot].shutdown_reader)
2390 return reader_table[slot].shutdown_reader (slot);
2391 return SW_HOST_NOT_SUPPORTED;
2394 /* Enumerate all readers and return information on whether this reader
2395 is in use. The caller should start with SLOT set to 0 and
2396 increment it with each call until an error is returned. */
2398 apdu_enum_reader (int slot, int *used)
2400 if (slot < 0 || slot >= MAX_READER)
2401 return SW_HOST_NO_DRIVER;
2402 *used = reader_table[slot].used;
2403 return 0;
2406 /* Do a reset for the card in reader at SLOT. */
2408 apdu_reset (int slot)
2410 int sw;
2412 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2413 return SW_HOST_NO_DRIVER;
2415 if ((sw = lock_slot (slot)))
2416 return sw;
2418 reader_table[slot].last_status = 0;
2419 if (reader_table[slot].reset_reader)
2420 sw = reader_table[slot].reset_reader (slot);
2422 if (!sw)
2424 /* If we got to here we know that a card is present
2425 and usable. Thus remember this. */
2426 reader_table[slot].last_status = (1|2|4| 0x8000);
2429 unlock_slot (slot);
2430 return sw;
2434 /* Activate a card if it has not yet been done. This is a kind of
2435 reset-if-required. It is useful to test for presence of a card
2436 before issuing a bunch of apdu commands. It does not wait on a
2437 locked card. */
2439 apdu_activate (int slot)
2441 int sw;
2442 unsigned int s;
2444 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2445 return SW_HOST_NO_DRIVER;
2447 if ((sw = trylock_slot (slot)))
2448 return sw;
2450 if (reader_table[slot].get_status_reader)
2451 sw = reader_table[slot].get_status_reader (slot, &s);
2453 if (!sw)
2455 if (!(s & 2)) /* Card not present. */
2456 sw = SW_HOST_NO_CARD;
2457 else if ( ((s & 2) && !(s & 4))
2458 || !reader_table[slot].atrlen )
2460 /* We don't have an ATR or a card is present though inactive:
2461 do a reset now. */
2462 if (reader_table[slot].reset_reader)
2464 reader_table[slot].last_status = 0;
2465 sw = reader_table[slot].reset_reader (slot);
2466 if (!sw)
2468 /* If we got to here we know that a card is present
2469 and usable. Thus remember this. */
2470 reader_table[slot].last_status = (1|2|4| 0x8000);
2476 unlock_slot (slot);
2477 return sw;
2482 unsigned char *
2483 apdu_get_atr (int slot, size_t *atrlen)
2485 unsigned char *buf;
2487 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2488 return NULL;
2490 buf = xtrymalloc (reader_table[slot].atrlen);
2491 if (!buf)
2492 return NULL;
2493 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2494 *atrlen = reader_table[slot].atrlen;
2495 return buf;
2500 /* Retrieve the status for SLOT. The function does only wait for the
2501 card to become available if HANG is set to true. On success the
2502 bits in STATUS will be set to
2504 bit 0 = card present and usable
2505 bit 1 = card present
2506 bit 2 = card active
2507 bit 3 = card access locked [not yet implemented]
2509 For must application, testing bit 0 is sufficient.
2511 CHANGED will receive the value of the counter tracking the number
2512 of card insertions. This value may be used to detect a card
2513 change.
2516 apdu_get_status (int slot, int hang,
2517 unsigned int *status, unsigned int *changed)
2519 int sw;
2520 unsigned int s;
2522 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2523 return SW_HOST_NO_DRIVER;
2525 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2526 return sw;
2528 if (reader_table[slot].get_status_reader)
2529 sw = reader_table[slot].get_status_reader (slot, &s);
2531 unlock_slot (slot);
2533 if (sw)
2535 reader_table[slot].last_status = 0;
2536 return sw;
2539 /* Keep track of changes. We use one extra bit to test whether we
2540 have checked the status at least once. */
2541 if ( s != (reader_table[slot].last_status & 0x07ff)
2542 || !reader_table[slot].last_status )
2544 reader_table[slot].change_counter++;
2545 /* Make sure that the ATR is invalid so that a reset will be by
2546 activate. */
2547 reader_table[slot].atrlen = 0;
2549 reader_table[slot].last_status = (s | 0x8000);
2551 if (status)
2552 *status = s;
2553 if (changed)
2554 *changed = reader_table[slot].change_counter;
2555 return 0;
2559 /* Check whether the reader supports the ISO command code COMMAND on
2560 the keypad. Return 0 on success. For a description of the pin
2561 parameters, see ccid-driver.c */
2563 apdu_check_keypad (int slot, int command, int pin_mode,
2564 int pinlen_min, int pinlen_max, int pin_padlen)
2566 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2567 return SW_HOST_NO_DRIVER;
2569 if (reader_table[slot].check_keypad)
2570 return reader_table[slot].check_keypad (slot, command,
2571 pin_mode, pinlen_min, pinlen_max,
2572 pin_padlen);
2573 else
2574 return SW_HOST_NOT_SUPPORTED;
2578 /* Dispatcher for the actual send_apdu function. Note, that this
2579 function should be called in locked state. */
2580 static int
2581 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2582 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2584 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2585 return SW_HOST_NO_DRIVER;
2587 if (reader_table[slot].send_apdu_reader)
2588 return reader_table[slot].send_apdu_reader (slot,
2589 apdu, apdulen,
2590 buffer, buflen, pininfo);
2591 else
2592 return SW_HOST_NOT_SUPPORTED;
2596 /* Core APDU trabceiver function. Parameters are described at
2597 apdu_send_le with the exception of PININFO which indicates keypad
2598 related operations if not NULL. */
2599 static int
2600 send_le (int slot, int class, int ins, int p0, int p1,
2601 int lc, const char *data, int le,
2602 unsigned char **retbuf, size_t *retbuflen,
2603 struct pininfo_s *pininfo)
2605 #define RESULTLEN 258
2606 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2607 the driver. */
2608 size_t resultlen;
2609 unsigned char apdu[5+256+1];
2610 size_t apdulen;
2611 int sw;
2612 long rc; /* We need a long here due to PC/SC. */
2613 int did_exact_length_hack = 0;
2615 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2616 return SW_HOST_NO_DRIVER;
2618 if (DBG_CARD_IO)
2619 log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
2620 class, ins, p0, p1, lc, le);
2622 if (lc != -1 && (lc > 255 || lc < 0))
2623 return SW_WRONG_LENGTH;
2624 if (le != -1 && (le > 256 || le < 0))
2625 return SW_WRONG_LENGTH;
2626 if ((!data && lc != -1) || (data && lc == -1))
2627 return SW_HOST_INV_VALUE;
2629 if ((sw = lock_slot (slot)))
2630 return sw;
2632 apdulen = 0;
2633 apdu[apdulen++] = class;
2634 apdu[apdulen++] = ins;
2635 apdu[apdulen++] = p0;
2636 apdu[apdulen++] = p1;
2637 if (lc != -1)
2639 apdu[apdulen++] = lc;
2640 memcpy (apdu+apdulen, data, lc);
2641 apdulen += lc;
2642 /* T=0 does not allow the use of Lc together with Le; thus
2643 disable Le in this case. */
2644 if (reader_table[slot].is_t0)
2645 le = -1;
2647 if (le != -1)
2648 apdu[apdulen++] = le; /* Truncation is okay because 0 means 256. */
2649 assert (sizeof (apdu) >= apdulen);
2650 /* As safeguard don't pass any garbage from the stack to the driver. */
2651 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2652 exact_length_hack:
2653 resultlen = RESULTLEN;
2654 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2655 if (rc || resultlen < 2)
2657 log_error ("apdu_send_simple(%d) failed: %s\n",
2658 slot, apdu_strerror (rc));
2659 unlock_slot (slot);
2660 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2662 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2663 if (!did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
2665 apdu[apdulen-1] = (sw & 0x00ff);
2666 did_exact_length_hack = 1;
2667 goto exact_length_hack;
2670 /* Store away the returned data but strip the statusword. */
2671 resultlen -= 2;
2672 if (DBG_CARD_IO)
2674 log_debug (" response: sw=%04X datalen=%d\n",
2675 sw, (unsigned int)resultlen);
2676 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2677 log_printhex (" dump: ", result, resultlen);
2680 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2682 if (retbuf)
2684 *retbuf = xtrymalloc (resultlen? resultlen : 1);
2685 if (!*retbuf)
2687 unlock_slot (slot);
2688 return SW_HOST_OUT_OF_CORE;
2690 *retbuflen = resultlen;
2691 memcpy (*retbuf, result, resultlen);
2694 else if ((sw & 0xff00) == SW_MORE_DATA)
2696 unsigned char *p = NULL, *tmp;
2697 size_t bufsize = 4096;
2699 /* It is likely that we need to return much more data, so we
2700 start off with a large buffer. */
2701 if (retbuf)
2703 *retbuf = p = xtrymalloc (bufsize);
2704 if (!*retbuf)
2706 unlock_slot (slot);
2707 return SW_HOST_OUT_OF_CORE;
2709 assert (resultlen < bufsize);
2710 memcpy (p, result, resultlen);
2711 p += resultlen;
2716 int len = (sw & 0x00ff);
2718 if (DBG_CARD_IO)
2719 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2720 slot, len);
2721 apdulen = 0;
2722 apdu[apdulen++] = class;
2723 apdu[apdulen++] = 0xC0;
2724 apdu[apdulen++] = 0;
2725 apdu[apdulen++] = 0;
2726 apdu[apdulen++] = len;
2727 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2728 resultlen = RESULTLEN;
2729 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2730 if (rc || resultlen < 2)
2732 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2733 slot, apdu_strerror (rc));
2734 unlock_slot (slot);
2735 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2737 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2738 resultlen -= 2;
2739 if (DBG_CARD_IO)
2741 log_debug (" more: sw=%04X datalen=%d\n",
2742 sw, (unsigned int)resultlen);
2743 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2744 log_printhex (" dump: ", result, resultlen);
2747 if ((sw & 0xff00) == SW_MORE_DATA
2748 || sw == SW_SUCCESS
2749 || sw == SW_EOF_REACHED )
2751 if (retbuf && resultlen)
2753 if (p - *retbuf + resultlen > bufsize)
2755 bufsize += resultlen > 4096? resultlen: 4096;
2756 tmp = xtryrealloc (*retbuf, bufsize);
2757 if (!tmp)
2759 unlock_slot (slot);
2760 return SW_HOST_OUT_OF_CORE;
2762 p = tmp + (p - *retbuf);
2763 *retbuf = tmp;
2765 memcpy (p, result, resultlen);
2766 p += resultlen;
2769 else
2770 log_info ("apdu_send_simple(%d) "
2771 "got unexpected status %04X from get response\n",
2772 slot, sw);
2774 while ((sw & 0xff00) == SW_MORE_DATA);
2776 if (retbuf)
2778 *retbuflen = p - *retbuf;
2779 tmp = xtryrealloc (*retbuf, *retbuflen);
2780 if (tmp)
2781 *retbuf = tmp;
2785 unlock_slot (slot);
2787 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2788 log_printhex (" dump: ", *retbuf, *retbuflen);
2790 return sw;
2791 #undef RESULTLEN
2794 /* Send an APDU to the card in SLOT. The APDU is created from all
2795 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2796 for LC won't sent this field and the data field; in this case DATA
2797 must also be passed as NULL. The return value is the status word
2798 or -1 for an invalid SLOT or other non card related error. If
2799 RETBUF is not NULL, it will receive an allocated buffer with the
2800 returned data. The length of that data will be put into
2801 *RETBUFLEN. The caller is reponsible for releasing the buffer even
2802 in case of errors. */
2804 apdu_send_le(int slot, int class, int ins, int p0, int p1,
2805 int lc, const char *data, int le,
2806 unsigned char **retbuf, size_t *retbuflen)
2808 return send_le (slot, class, ins, p0, p1,
2809 lc, data, le,
2810 retbuf, retbuflen,
2811 NULL);
2815 /* Send an APDU to the card in SLOT. The APDU is created from all
2816 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2817 LC won't sent this field and the data field; in this case DATA must
2818 also be passed as NULL. The return value is the status word or -1
2819 for an invalid SLOT or other non card related error. If RETBUF is
2820 not NULL, it will receive an allocated buffer with the returned
2821 data. The length of that data will be put into *RETBUFLEN. The
2822 caller is reponsible for releasing the buffer even in case of
2823 errors. */
2825 apdu_send (int slot, int class, int ins, int p0, int p1,
2826 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2828 return send_le (slot, class, ins, p0, p1, lc, data, 256,
2829 retbuf, retbuflen, NULL);
2832 /* Send an APDU to the card in SLOT. The APDU is created from all
2833 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2834 LC won't sent this field and the data field; in this case DATA must
2835 also be passed as NULL. The return value is the status word or -1
2836 for an invalid SLOT or other non card related error. No data will be
2837 returned. */
2839 apdu_send_simple (int slot, int class, int ins, int p0, int p1,
2840 int lc, const char *data)
2842 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL);
2846 /* Same as apdu_send_simple but uses the keypad of the reader. */
2848 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
2849 int lc, const char *data,
2850 int pin_mode,
2851 int pinlen_min, int pinlen_max, int pin_padlen)
2853 struct pininfo_s pininfo;
2855 pininfo.mode = pin_mode;
2856 pininfo.minlen = pinlen_min;
2857 pininfo.maxlen = pinlen_max;
2858 pininfo.padlen = pin_padlen;
2859 return send_le (slot, class, ins, p0, p1, lc, data, -1,
2860 NULL, NULL, &pininfo);
2864 /* This is a more generic version of the apdu sending routine. It
2865 takes an already formatted APDU in APDUDATA or length APDUDATALEN
2866 and returns the with the APDU including the status word. With
2867 HANDLE_MORE set to true this function will handle the MORE DATA
2868 status and return all APDUs concatenated with one status word at
2869 the end. The function does not return a regular status word but 0
2870 on success. If the slot is locked, the function returns
2871 immediately with an error. */
2873 apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
2874 int handle_more,
2875 unsigned char **retbuf, size_t *retbuflen)
2877 #define RESULTLEN 258
2878 unsigned char apdu[5+256+1];
2879 size_t apdulen;
2880 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2881 the driver. */
2882 size_t resultlen;
2883 int sw;
2884 long rc; /* we need a long here due to PC/SC. */
2885 int class;
2887 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2888 return SW_HOST_NO_DRIVER;
2890 if ((sw = trylock_slot (slot)))
2891 return sw;
2893 /* We simply trunctate a too long APDU. */
2894 if (apdudatalen > sizeof apdu)
2895 apdudatalen = sizeof apdu;
2896 apdulen = apdudatalen;
2897 memcpy (apdu, apdudata, apdudatalen);
2898 class = apdulen? *apdu : 0;
2900 resultlen = RESULTLEN;
2901 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2902 if (rc || resultlen < 2)
2904 log_error ("apdu_send_direct(%d) failed: %s\n",
2905 slot, apdu_strerror (rc));
2906 unlock_slot (slot);
2907 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2909 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2910 /* Store away the returned data but strip the statusword. */
2911 resultlen -= 2;
2912 if (DBG_CARD_IO)
2914 log_debug (" response: sw=%04X datalen=%d\n",
2915 sw, (unsigned int)resultlen);
2916 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2917 log_printhex (" dump: ", result, resultlen);
2920 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
2922 unsigned char *p = NULL, *tmp;
2923 size_t bufsize = 4096;
2925 /* It is likely that we need to return much more data, so we
2926 start off with a large buffer. */
2927 if (retbuf)
2929 *retbuf = p = xtrymalloc (bufsize + 2);
2930 if (!*retbuf)
2932 unlock_slot (slot);
2933 return SW_HOST_OUT_OF_CORE;
2935 assert (resultlen < bufsize);
2936 memcpy (p, result, resultlen);
2937 p += resultlen;
2942 int len = (sw & 0x00ff);
2944 if (DBG_CARD_IO)
2945 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
2946 slot, len);
2947 apdulen = 0;
2948 apdu[apdulen++] = class;
2949 apdu[apdulen++] = 0xC0;
2950 apdu[apdulen++] = 0;
2951 apdu[apdulen++] = 0;
2952 apdu[apdulen++] = len;
2953 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2954 resultlen = RESULTLEN;
2955 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2956 if (rc || resultlen < 2)
2958 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
2959 slot, apdu_strerror (rc));
2960 unlock_slot (slot);
2961 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2963 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2964 resultlen -= 2;
2965 if (DBG_CARD_IO)
2967 log_debug (" more: sw=%04X datalen=%d\n",
2968 sw, (unsigned int)resultlen);
2969 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2970 log_printhex (" dump: ", result, resultlen);
2973 if ((sw & 0xff00) == SW_MORE_DATA
2974 || sw == SW_SUCCESS
2975 || sw == SW_EOF_REACHED )
2977 if (retbuf && resultlen)
2979 if (p - *retbuf + resultlen > bufsize)
2981 bufsize += resultlen > 4096? resultlen: 4096;
2982 tmp = xtryrealloc (*retbuf, bufsize + 2);
2983 if (!tmp)
2985 unlock_slot (slot);
2986 return SW_HOST_OUT_OF_CORE;
2988 p = tmp + (p - *retbuf);
2989 *retbuf = tmp;
2991 memcpy (p, result, resultlen);
2992 p += resultlen;
2995 else
2996 log_info ("apdu_send_sdirect(%d) "
2997 "got unexpected status %04X from get response\n",
2998 slot, sw);
3000 while ((sw & 0xff00) == SW_MORE_DATA);
3002 if (retbuf)
3004 *retbuflen = p - *retbuf;
3005 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3006 if (tmp)
3007 *retbuf = tmp;
3010 else
3012 if (retbuf)
3014 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3015 if (!*retbuf)
3017 unlock_slot (slot);
3018 return SW_HOST_OUT_OF_CORE;
3020 *retbuflen = resultlen;
3021 memcpy (*retbuf, result, resultlen);
3025 unlock_slot (slot);
3027 /* Append the status word - we reseved the two extra bytes while
3028 allocating the buffer. */
3029 if (retbuf)
3031 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3032 (*retbuf)[(*retbuflen)++] = sw;
3035 if (DBG_CARD_IO && retbuf)
3036 log_printhex (" dump: ", *retbuf, *retbuflen);
3038 return 0;
3039 #undef RESULTLEN