Implement decryption for TCOS 3 cards.
[gnupg.git] / scd / apdu.c
blobd63157ce7fcb3b875626a6baf83789131b44e062
1 /* apdu.c - ISO 7816 APDU functions and low level I/O
2 * Copyright (C) 2003, 2004, 2008, 2009 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 * $Id$
22 /* NOTE: This module is also used by other software, thus the use of
23 the macro USE_GNU_PTH is mandatory. For GnuPG this macro is
24 guaranteed to be defined true. */
26 #include <config.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <signal.h>
33 #ifdef USE_GNU_PTH
34 # include <unistd.h>
35 # include <fcntl.h>
36 # include <pth.h>
37 #endif
40 /* If requested include the definitions for the remote APDU protocol
41 code. */
42 #ifdef USE_G10CODE_RAPDU
43 #include "rapdu.h"
44 #endif /*USE_G10CODE_RAPDU*/
46 #if defined(GNUPG_SCD_MAIN_HEADER)
47 #include GNUPG_SCD_MAIN_HEADER
48 #elif GNUPG_MAJOR_VERSION == 1
49 /* This is used with GnuPG version < 1.9. The code has been source
50 copied from the current GnuPG >= 1.9 and is maintained over
51 there. */
52 #include "options.h"
53 #include "errors.h"
54 #include "memory.h"
55 #include "util.h"
56 #include "i18n.h"
57 #include "cardglue.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
59 #include "scdaemon.h"
60 #include "exechelp.h"
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
63 #include "apdu.h"
64 #include "ccid-driver.h"
67 /* Due to conflicting use of threading libraries we usually can't link
68 against libpcsclite. Instead we use a wrapper program. */
69 #ifdef USE_GNU_PTH
70 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
71 #define NEED_PCSC_WRAPPER 1
72 #endif
73 #endif
76 #define MAX_READER 4 /* Number of readers we support concurrently. */
79 #if defined(_WIN32) || defined(__CYGWIN__)
80 #define DLSTDCALL __stdcall
81 #else
82 #define DLSTDCALL
83 #endif
86 /* Helper to pass parameters related to keypad based operations. */
87 struct pininfo_s
89 int mode;
90 int minlen;
91 int maxlen;
92 int padlen;
95 /* A structure to collect information pertaining to one reader
96 slot. */
97 struct reader_table_s {
98 int used; /* True if slot is used. */
99 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
101 /* Function pointers intialized to the various backends. */
102 int (*connect_card)(int);
103 int (*disconnect_card)(int);
104 int (*close_reader)(int);
105 int (*shutdown_reader)(int);
106 int (*reset_reader)(int);
107 int (*get_status_reader)(int, unsigned int *);
108 int (*send_apdu_reader)(int,unsigned char *,size_t,
109 unsigned char *, size_t *, struct pininfo_s *);
110 int (*check_keypad)(int, int, int, int, int, int);
111 void (*dump_status_reader)(int);
113 struct {
114 ccid_driver_t handle;
115 } ccid;
116 struct {
117 unsigned long context;
118 unsigned long card;
119 unsigned long protocol;
120 #ifdef NEED_PCSC_WRAPPER
121 int req_fd;
122 int rsp_fd;
123 pid_t pid;
124 #endif /*NEED_PCSC_WRAPPER*/
125 } pcsc;
126 #ifdef USE_G10CODE_RAPDU
127 struct {
128 rapdu_t handle;
129 } rapdu;
130 #endif /*USE_G10CODE_RAPDU*/
131 char *rdrname; /* Name of the connected reader or NULL if unknown. */
132 int any_status; /* True if we have seen any status. */
133 int last_status;
134 int status;
135 int is_t0; /* True if we know that we are running T=0. */
136 unsigned char atr[33];
137 size_t atrlen; /* A zero length indicates that the ATR has
138 not yet been read; i.e. the card is not
139 ready for use. */
140 unsigned int change_counter;
141 #ifdef USE_GNU_PTH
142 int lock_initialized;
143 pth_mutex_t lock;
144 #endif
146 typedef struct reader_table_s *reader_table_t;
148 /* A global table to keep track of active readers. */
149 static struct reader_table_s reader_table[MAX_READER];
152 /* ct API function pointer. */
153 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
154 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
155 unsigned char *sad, unsigned short lc,
156 unsigned char *cmd, unsigned short *lr,
157 unsigned char *rsp);
158 static char (* DLSTDCALL CT_close) (unsigned short ctn);
160 /* PC/SC constants and function pointer. */
161 #define PCSC_SCOPE_USER 0
162 #define PCSC_SCOPE_TERMINAL 1
163 #define PCSC_SCOPE_SYSTEM 2
164 #define PCSC_SCOPE_GLOBAL 3
166 #define PCSC_PROTOCOL_T0 1
167 #define PCSC_PROTOCOL_T1 2
168 #define PCSC_PROTOCOL_RAW 4
170 #define PCSC_SHARE_EXCLUSIVE 1
171 #define PCSC_SHARE_SHARED 2
172 #define PCSC_SHARE_DIRECT 3
174 #define PCSC_LEAVE_CARD 0
175 #define PCSC_RESET_CARD 1
176 #define PCSC_UNPOWER_CARD 2
177 #define PCSC_EJECT_CARD 3
179 #define PCSC_UNKNOWN 0x0001
180 #define PCSC_ABSENT 0x0002 /* Card is absent. */
181 #define PCSC_PRESENT 0x0004 /* Card is present. */
182 #define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
183 #define PCSC_POWERED 0x0010 /* Card is powered. */
184 #define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
185 #define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
187 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
188 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
189 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
190 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
191 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
192 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
193 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
194 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
195 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
196 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
197 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
199 /* Some PC/SC error codes. */
200 #define PCSC_E_CANCELLED 0x80100002
201 #define PCSC_E_CANT_DISPOSE 0x8010000E
202 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
203 #define PCSC_E_INVALID_ATR 0x80100015
204 #define PCSC_E_INVALID_HANDLE 0x80100003
205 #define PCSC_E_INVALID_PARAMETER 0x80100004
206 #define PCSC_E_INVALID_TARGET 0x80100005
207 #define PCSC_E_INVALID_VALUE 0x80100011
208 #define PCSC_E_NO_MEMORY 0x80100006
209 #define PCSC_E_UNKNOWN_READER 0x80100009
210 #define PCSC_E_TIMEOUT 0x8010000A
211 #define PCSC_E_SHARING_VIOLATION 0x8010000B
212 #define PCSC_E_NO_SMARTCARD 0x8010000C
213 #define PCSC_E_UNKNOWN_CARD 0x8010000D
214 #define PCSC_E_PROTO_MISMATCH 0x8010000F
215 #define PCSC_E_NOT_READY 0x80100010
216 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
217 #define PCSC_E_NOT_TRANSACTED 0x80100016
218 #define PCSC_E_READER_UNAVAILABLE 0x80100017
219 #define PCSC_W_REMOVED_CARD 0x80100069
221 /* The PC/SC error is defined as a long as per specs. Due to left
222 shifts bit 31 will get sign extended. We use this mask to fix
223 it. */
224 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
227 struct pcsc_io_request_s
229 unsigned long protocol;
230 unsigned long pci_len;
233 typedef struct pcsc_io_request_s *pcsc_io_request_t;
235 struct pcsc_readerstate_s
237 const char *reader;
238 void *user_data;
239 unsigned long current_state;
240 unsigned long event_state;
241 unsigned long atrlen;
242 unsigned char atr[33];
245 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
247 long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
248 const void *reserved1,
249 const void *reserved2,
250 unsigned long *r_context);
251 long (* DLSTDCALL pcsc_release_context) (unsigned long context);
252 long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
253 const char *groups,
254 char *readers, unsigned long*readerslen);
255 long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
256 unsigned long timeout,
257 pcsc_readerstate_t readerstates,
258 unsigned long nreaderstates);
259 long (* DLSTDCALL pcsc_connect) (unsigned long context,
260 const char *reader,
261 unsigned long share_mode,
262 unsigned long preferred_protocols,
263 unsigned long *r_card,
264 unsigned long *r_active_protocol);
265 long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
266 unsigned long share_mode,
267 unsigned long preferred_protocols,
268 unsigned long initialization,
269 unsigned long *r_active_protocol);
270 long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
271 unsigned long disposition);
272 long (* DLSTDCALL pcsc_status) (unsigned long card,
273 char *reader, unsigned long *readerlen,
274 unsigned long *r_state,
275 unsigned long *r_protocol,
276 unsigned char *atr, unsigned long *atrlen);
277 long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
278 long (* DLSTDCALL pcsc_end_transaction) (unsigned long card,
279 unsigned long disposition);
280 long (* DLSTDCALL pcsc_transmit) (unsigned long card,
281 const pcsc_io_request_t send_pci,
282 const unsigned char *send_buffer,
283 unsigned long send_len,
284 pcsc_io_request_t recv_pci,
285 unsigned char *recv_buffer,
286 unsigned long *recv_len);
287 long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
288 unsigned long timeout);
291 /* Prototypes. */
292 static int pcsc_get_status (int slot, unsigned int *status);
293 static int reset_pcsc_reader (int slot);
294 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
295 unsigned int *status,
296 unsigned int *changed);
301 Helper
305 /* Find an unused reader slot for PORTSTR and put it into the reader
306 table. Return -1 on error or the index into the reader table. */
307 static int
308 new_reader_slot (void)
310 int i, reader = -1;
312 for (i=0; i < MAX_READER; i++)
314 if (!reader_table[i].used && reader == -1)
315 reader = i;
317 if (reader == -1)
319 log_error ("new_reader_slot: out of slots\n");
320 return -1;
322 #ifdef USE_GNU_PTH
323 if (!reader_table[reader].lock_initialized)
325 if (!pth_mutex_init (&reader_table[reader].lock))
327 log_error ("error initializing mutex: %s\n", strerror (errno));
328 return -1;
330 reader_table[reader].lock_initialized = 1;
332 #endif /*USE_GNU_PTH*/
333 reader_table[reader].connect_card = NULL;
334 reader_table[reader].disconnect_card = NULL;
335 reader_table[reader].close_reader = NULL;
336 reader_table[reader].shutdown_reader = NULL;
337 reader_table[reader].reset_reader = NULL;
338 reader_table[reader].get_status_reader = NULL;
339 reader_table[reader].send_apdu_reader = NULL;
340 reader_table[reader].check_keypad = NULL;
341 reader_table[reader].dump_status_reader = NULL;
343 reader_table[reader].used = 1;
344 reader_table[reader].any_status = 0;
345 reader_table[reader].last_status = 0;
346 reader_table[reader].is_t0 = 1;
347 #ifdef NEED_PCSC_WRAPPER
348 reader_table[reader].pcsc.req_fd = -1;
349 reader_table[reader].pcsc.rsp_fd = -1;
350 reader_table[reader].pcsc.pid = (pid_t)(-1);
351 #endif
353 return reader;
357 static void
358 dump_reader_status (int slot)
360 if (!opt.verbose)
361 return;
363 if (reader_table[slot].dump_status_reader)
364 reader_table[slot].dump_status_reader (slot);
366 if (reader_table[slot].status != -1
367 && reader_table[slot].atrlen)
369 log_info ("slot %d: ATR=", slot);
370 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
376 static const char *
377 host_sw_string (long err)
379 switch (err)
381 case 0: return "okay";
382 case SW_HOST_OUT_OF_CORE: return "out of core";
383 case SW_HOST_INV_VALUE: return "invalid value";
384 case SW_HOST_NO_DRIVER: return "no driver";
385 case SW_HOST_NOT_SUPPORTED: return "not supported";
386 case SW_HOST_LOCKING_FAILED: return "locking failed";
387 case SW_HOST_BUSY: return "busy";
388 case SW_HOST_NO_CARD: return "no card";
389 case SW_HOST_CARD_INACTIVE: return "card inactive";
390 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
391 case SW_HOST_GENERAL_ERROR: return "general error";
392 case SW_HOST_NO_READER: return "no reader";
393 case SW_HOST_ABORTED: return "aborted";
394 case SW_HOST_NO_KEYPAD: return "no keypad";
395 case SW_HOST_ALREADY_CONNECTED: return "already connected";
396 default: return "unknown host status error";
401 const char *
402 apdu_strerror (int rc)
404 switch (rc)
406 case SW_EOF_REACHED : return "eof reached";
407 case SW_EEPROM_FAILURE : return "eeprom failure";
408 case SW_WRONG_LENGTH : return "wrong length";
409 case SW_CHV_WRONG : return "CHV wrong";
410 case SW_CHV_BLOCKED : return "CHV blocked";
411 case SW_USE_CONDITIONS : return "use conditions not satisfied";
412 case SW_BAD_PARAMETER : return "bad parameter";
413 case SW_NOT_SUPPORTED : return "not supported";
414 case SW_FILE_NOT_FOUND : return "file not found";
415 case SW_RECORD_NOT_FOUND:return "record not found";
416 case SW_REF_NOT_FOUND : return "reference not found";
417 case SW_BAD_LC : return "bad Lc";
418 case SW_BAD_P0_P1 : return "bad P0 or P1";
419 case SW_INS_NOT_SUP : return "instruction not supported";
420 case SW_CLA_NOT_SUP : return "class not supported";
421 case SW_SUCCESS : return "success";
422 default:
423 if ((rc & ~0x00ff) == SW_MORE_DATA)
424 return "more data available";
425 if ( (rc & 0x10000) )
426 return host_sw_string (rc);
427 return "unknown status error";
434 ct API Interface
437 static const char *
438 ct_error_string (long err)
440 switch (err)
442 case 0: return "okay";
443 case -1: return "invalid data";
444 case -8: return "ct error";
445 case -10: return "transmission error";
446 case -11: return "memory allocation error";
447 case -128: return "HTSI error";
448 default: return "unknown CT-API error";
453 static void
454 ct_dump_reader_status (int slot)
456 log_info ("reader slot %d: %s\n", slot,
457 reader_table[slot].status == 1? "Processor ICC present" :
458 reader_table[slot].status == 0? "Memory ICC present" :
459 "ICC not present" );
463 /* Wait for the card in SLOT and activate it. Return a status word
464 error or 0 on success. */
465 static int
466 ct_activate_card (int slot)
468 int rc;
469 unsigned char dad[1], sad[1], cmd[11], buf[256];
470 unsigned short buflen;
472 /* Check whether card has been inserted. */
473 dad[0] = 1; /* Destination address: CT. */
474 sad[0] = 2; /* Source address: Host. */
476 cmd[0] = 0x20; /* Class byte. */
477 cmd[1] = 0x13; /* Request status. */
478 cmd[2] = 0x00; /* From kernel. */
479 cmd[3] = 0x80; /* Return card's DO. */
480 cmd[4] = 0x00;
482 buflen = DIM(buf);
484 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
485 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
487 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
488 slot, ct_error_string (rc));
489 return SW_HOST_CARD_IO_ERROR;
492 /* Connected, now activate the card. */
493 dad[0] = 1; /* Destination address: CT. */
494 sad[0] = 2; /* Source address: Host. */
496 cmd[0] = 0x20; /* Class byte. */
497 cmd[1] = 0x12; /* Request ICC. */
498 cmd[2] = 0x01; /* From first interface. */
499 cmd[3] = 0x01; /* Return card's ATR. */
500 cmd[4] = 0x00;
502 buflen = DIM(buf);
504 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
505 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
507 log_error ("ct_activate_card(%d): activation failed: %s\n",
508 slot, ct_error_string (rc));
509 if (!rc)
510 log_printhex (" received data:", buf, buflen);
511 return SW_HOST_CARD_IO_ERROR;
514 /* Store the type and the ATR. */
515 if (buflen - 2 > DIM (reader_table[0].atr))
517 log_error ("ct_activate_card(%d): ATR too long\n", slot);
518 return SW_HOST_CARD_IO_ERROR;
521 reader_table[slot].status = buf[buflen - 1];
522 memcpy (reader_table[slot].atr, buf, buflen - 2);
523 reader_table[slot].atrlen = buflen - 2;
524 return 0;
528 static int
529 close_ct_reader (int slot)
531 CT_close (slot);
532 reader_table[slot].used = 0;
533 return 0;
536 static int
537 reset_ct_reader (int slot)
539 /* FIXME: Check is this is sufficient do do a reset. */
540 return ct_activate_card (slot);
544 static int
545 ct_get_status (int slot, unsigned int *status)
547 (void)slot;
548 /* The status we returned is wrong but we don't care becuase ctAPI
549 is not anymore required. */
550 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
551 return 0;
554 /* Actually send the APDU of length APDULEN to SLOT and return a
555 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
556 set to BUFLEN. Returns: CT API error code. */
557 static int
558 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
559 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
561 int rc;
562 unsigned char dad[1], sad[1];
563 unsigned short ctbuflen;
565 (void)pininfo;
567 /* If we don't have an ATR, we need to reset the reader first. */
568 if (!reader_table[slot].atrlen
569 && (rc = reset_ct_reader (slot)))
570 return rc;
572 dad[0] = 0; /* Destination address: Card. */
573 sad[0] = 2; /* Source address: Host. */
574 ctbuflen = *buflen;
575 if (DBG_CARD_IO)
576 log_printhex (" CT_data:", apdu, apdulen);
577 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
578 *buflen = ctbuflen;
580 return rc? SW_HOST_CARD_IO_ERROR: 0;
585 /* Open a reader and return an internal handle for it. PORT is a
586 non-negative value with the port number of the reader. USB readers
587 do have port numbers starting at 32769. */
588 static int
589 open_ct_reader (int port)
591 int rc, reader;
593 if (port < 0 || port > 0xffff)
595 log_error ("open_ct_reader: invalid port %d requested\n", port);
596 return -1;
598 reader = new_reader_slot ();
599 if (reader == -1)
600 return reader;
601 reader_table[reader].port = port;
603 rc = CT_init (reader, (unsigned short)port);
604 if (rc)
606 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
607 port, ct_error_string (rc));
608 reader_table[reader].used = 0;
609 return -1;
612 /* Only try to activate the card. */
613 rc = ct_activate_card (reader);
614 if (rc)
616 reader_table[reader].atrlen = 0;
617 rc = 0;
620 reader_table[reader].close_reader = close_ct_reader;
621 reader_table[reader].reset_reader = reset_ct_reader;
622 reader_table[reader].get_status_reader = ct_get_status;
623 reader_table[reader].send_apdu_reader = ct_send_apdu;
624 reader_table[reader].check_keypad = NULL;
625 reader_table[reader].dump_status_reader = ct_dump_reader_status;
627 dump_reader_status (reader);
628 return reader;
633 PC/SC Interface
636 #ifdef NEED_PCSC_WRAPPER
637 static int
638 writen (int fd, const void *buf, size_t nbytes)
640 size_t nleft = nbytes;
641 int nwritten;
643 /* log_printhex (" writen:", buf, nbytes); */
645 while (nleft > 0)
647 #ifdef USE_GNU_PTH
648 nwritten = pth_write (fd, buf, nleft);
649 #else
650 nwritten = write (fd, buf, nleft);
651 #endif
652 if (nwritten < 0 && errno == EINTR)
653 continue;
654 if (nwritten < 0)
655 return -1;
656 nleft -= nwritten;
657 buf = (const char*)buf + nwritten;
659 return 0;
662 /* Read up to BUFLEN bytes from FD and return the number of bytes
663 actually read in NREAD. Returns -1 on error or 0 on success. */
664 static int
665 readn (int fd, void *buf, size_t buflen, size_t *nread)
667 size_t nleft = buflen;
668 int n;
669 /* void *orig_buf = buf; */
671 while (nleft > 0)
673 #ifdef USE_GNU_PTH
674 n = pth_read (fd, buf, nleft);
675 #else
676 n = read (fd, buf, nleft);
677 #endif
678 if (n < 0 && errno == EINTR)
679 continue;
680 if (n < 0)
681 return -1; /* read error. */
682 if (!n)
683 break; /* EOF */
684 nleft -= n;
685 buf = (char*)buf + n;
687 if (nread)
688 *nread = buflen - nleft;
690 /* log_printhex (" readn:", orig_buf, *nread); */
692 return 0;
694 #endif /*NEED_PCSC_WRAPPER*/
696 static const char *
697 pcsc_error_string (long err)
699 const char *s;
701 if (!err)
702 return "okay";
703 if ((err & 0x80100000) != 0x80100000)
704 return "invalid PC/SC error code";
705 err &= 0xffff;
706 switch (err)
708 case 0x0002: s = "cancelled"; break;
709 case 0x000e: s = "can't dispose"; break;
710 case 0x0008: s = "insufficient buffer"; break;
711 case 0x0015: s = "invalid ATR"; break;
712 case 0x0003: s = "invalid handle"; break;
713 case 0x0004: s = "invalid parameter"; break;
714 case 0x0005: s = "invalid target"; break;
715 case 0x0011: s = "invalid value"; break;
716 case 0x0006: s = "no memory"; break;
717 case 0x0013: s = "comm error"; break;
718 case 0x0001: s = "internal error"; break;
719 case 0x0014: s = "unknown error"; break;
720 case 0x0007: s = "waited too long"; break;
721 case 0x0009: s = "unknown reader"; break;
722 case 0x000a: s = "timeout"; break;
723 case 0x000b: s = "sharing violation"; break;
724 case 0x000c: s = "no smartcard"; break;
725 case 0x000d: s = "unknown card"; break;
726 case 0x000f: s = "proto mismatch"; break;
727 case 0x0010: s = "not ready"; break;
728 case 0x0012: s = "system cancelled"; break;
729 case 0x0016: s = "not transacted"; break;
730 case 0x0017: s = "reader unavailable"; break;
731 case 0x0065: s = "unsupported card"; break;
732 case 0x0066: s = "unresponsive card"; break;
733 case 0x0067: s = "unpowered card"; break;
734 case 0x0068: s = "reset card"; break;
735 case 0x0069: s = "removed card"; break;
736 case 0x006a: s = "inserted card"; break;
737 case 0x001f: s = "unsupported feature"; break;
738 case 0x0019: s = "PCI too small"; break;
739 case 0x001a: s = "reader unsupported"; break;
740 case 0x001b: s = "duplicate reader"; break;
741 case 0x001c: s = "card unsupported"; break;
742 case 0x001d: s = "no service"; break;
743 case 0x001e: s = "service stopped"; break;
744 default: s = "unknown PC/SC error code"; break;
746 return s;
749 /* Map PC/SC error codes to our special host status words. */
750 static int
751 pcsc_error_to_sw (long ec)
753 int rc;
755 switch ( PCSC_ERR_MASK (ec) )
757 case 0: rc = 0; break;
759 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
760 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
761 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
762 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
763 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
764 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
766 case PCSC_E_INVALID_TARGET:
767 case PCSC_E_INVALID_VALUE:
768 case PCSC_E_INVALID_HANDLE:
769 case PCSC_E_INVALID_PARAMETER:
770 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
772 default: rc = SW_HOST_GENERAL_ERROR; break;
775 return rc;
778 static void
779 dump_pcsc_reader_status (int slot)
781 if (reader_table[slot].pcsc.card)
783 log_info ("reader slot %d: active protocol:", slot);
784 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
785 log_printf (" T0");
786 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
787 log_printf (" T1");
788 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
789 log_printf (" raw");
790 log_printf ("\n");
792 else
793 log_info ("reader slot %d: not connected\n", slot);
797 #ifndef NEED_PCSC_WRAPPER
798 static int
799 pcsc_get_status_direct (int slot, unsigned int *status)
801 long err;
802 struct pcsc_readerstate_s rdrstates[1];
804 memset (rdrstates, 0, sizeof *rdrstates);
805 rdrstates[0].reader = reader_table[slot].rdrname;
806 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
807 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
809 rdrstates, 1);
810 if (err == PCSC_E_TIMEOUT)
811 err = 0; /* Timeout is no error error here. */
812 if (err)
814 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
815 pcsc_error_string (err), err);
816 return pcsc_error_to_sw (err);
819 /* log_debug */
820 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
821 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
822 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
823 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
824 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
825 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
826 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
827 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
828 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
829 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
830 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
832 *status = 0;
833 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
834 *status |= APDU_CARD_PRESENT;
835 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
836 *status |= APDU_CARD_ACTIVE;
837 #ifndef HAVE_W32_SYSTEM
838 /* We indicate a useful card if it is not in use by another
839 application. This is because we only use exclusive access
840 mode. */
841 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
842 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
843 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
844 *status |= APDU_CARD_USABLE;
845 #else
846 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
847 time when we are the only user (SCM SCR335) under Windows. */
848 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
849 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
850 *status |= APDU_CARD_USABLE;
851 #endif
853 return 0;
855 #endif /*!NEED_PCSC_WRAPPER*/
858 #ifdef NEED_PCSC_WRAPPER
859 static int
860 pcsc_get_status_wrapped (int slot, unsigned int *status)
862 long err;
863 reader_table_t slotp;
864 size_t len, full_len;
865 int i, n;
866 unsigned char msgbuf[9];
867 unsigned char buffer[16];
868 int sw = SW_HOST_CARD_IO_ERROR;
870 slotp = reader_table + slot;
872 if (slotp->pcsc.req_fd == -1
873 || slotp->pcsc.rsp_fd == -1
874 || slotp->pcsc.pid == (pid_t)(-1) )
876 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
877 return sw;
880 msgbuf[0] = 0x04; /* STATUS command. */
881 len = 0;
882 msgbuf[1] = (len >> 24);
883 msgbuf[2] = (len >> 16);
884 msgbuf[3] = (len >> 8);
885 msgbuf[4] = (len );
886 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
888 log_error ("error sending PC/SC STATUS request: %s\n",
889 strerror (errno));
890 goto command_failed;
893 /* Read the response. */
894 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
896 log_error ("error receiving PC/SC STATUS response: %s\n",
897 i? strerror (errno) : "premature EOF");
898 goto command_failed;
900 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
901 if (msgbuf[0] != 0x81 || len < 4)
903 log_error ("invalid response header from PC/SC received\n");
904 goto command_failed;
906 len -= 4; /* Already read the error code. */
907 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
908 | (msgbuf[7] << 8 ) | msgbuf[8]);
909 if (err)
911 log_error ("pcsc_status failed: %s (0x%lx)\n",
912 pcsc_error_string (err), err);
913 /* This is a proper error code, so return immediately. */
914 return pcsc_error_to_sw (err);
917 full_len = len;
919 /* The current version returns 3 words but we allow also for old
920 versions returning only 2 words. */
921 n = 12 < len ? 12 : len;
922 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
923 || (len != 8 && len != 12))
925 log_error ("error receiving PC/SC STATUS response: %s\n",
926 i? strerror (errno) : "premature EOF");
927 goto command_failed;
930 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
933 full_len -= len;
934 /* Newer versions of the wrapper might send more status bytes.
935 Read them. */
936 while (full_len)
938 unsigned char dummybuf[128];
940 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
941 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
943 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
944 i? strerror (errno) : "premature EOF");
945 goto command_failed;
947 full_len -= n;
950 /* We are lucky: The wrapper already returns the data in the
951 required format. */
952 *status = buffer[3];
953 return 0;
955 command_failed:
956 close (slotp->pcsc.req_fd);
957 close (slotp->pcsc.rsp_fd);
958 slotp->pcsc.req_fd = -1;
959 slotp->pcsc.rsp_fd = -1;
960 kill (slotp->pcsc.pid, SIGTERM);
961 slotp->pcsc.pid = (pid_t)(-1);
962 slotp->used = 0;
963 return sw;
965 #endif /*NEED_PCSC_WRAPPER*/
968 static int
969 pcsc_get_status (int slot, unsigned int *status)
971 #ifdef NEED_PCSC_WRAPPER
972 return pcsc_get_status_wrapped (slot, status);
973 #else
974 return pcsc_get_status_direct (slot, status);
975 #endif
979 #ifndef NEED_PCSC_WRAPPER
980 static int
981 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
982 unsigned char *buffer, size_t *buflen,
983 struct pininfo_s *pininfo)
985 long err;
986 struct pcsc_io_request_s send_pci;
987 unsigned long recv_len;
989 if (!reader_table[slot].atrlen
990 && (err = reset_pcsc_reader (slot)))
991 return err;
993 if (DBG_CARD_IO)
994 log_printhex (" PCSC_data:", apdu, apdulen);
996 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
997 send_pci.protocol = PCSC_PROTOCOL_T1;
998 else
999 send_pci.protocol = PCSC_PROTOCOL_T0;
1000 send_pci.pci_len = sizeof send_pci;
1001 recv_len = *buflen;
1002 err = pcsc_transmit (reader_table[slot].pcsc.card,
1003 &send_pci, apdu, apdulen,
1004 NULL, buffer, &recv_len);
1005 *buflen = recv_len;
1006 if (err)
1007 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1008 pcsc_error_string (err), err);
1010 return pcsc_error_to_sw (err);
1012 #endif /*!NEED_PCSC_WRAPPER*/
1015 #ifdef NEED_PCSC_WRAPPER
1016 static int
1017 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1018 unsigned char *buffer, size_t *buflen,
1019 struct pininfo_s *pininfo)
1021 long err;
1022 reader_table_t slotp;
1023 size_t len, full_len;
1024 int i, n;
1025 unsigned char msgbuf[9];
1026 int sw = SW_HOST_CARD_IO_ERROR;
1028 (void)pininfo;
1030 if (!reader_table[slot].atrlen
1031 && (err = reset_pcsc_reader (slot)))
1032 return err;
1034 if (DBG_CARD_IO)
1035 log_printhex (" PCSC_data:", apdu, apdulen);
1037 slotp = reader_table + slot;
1039 if (slotp->pcsc.req_fd == -1
1040 || slotp->pcsc.rsp_fd == -1
1041 || slotp->pcsc.pid == (pid_t)(-1) )
1043 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1044 return sw;
1047 msgbuf[0] = 0x03; /* TRANSMIT command. */
1048 len = apdulen;
1049 msgbuf[1] = (len >> 24);
1050 msgbuf[2] = (len >> 16);
1051 msgbuf[3] = (len >> 8);
1052 msgbuf[4] = (len );
1053 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1054 || writen (slotp->pcsc.req_fd, apdu, len))
1056 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1057 strerror (errno));
1058 goto command_failed;
1061 /* Read the response. */
1062 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1064 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1065 i? strerror (errno) : "premature EOF");
1066 goto command_failed;
1068 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1069 if (msgbuf[0] != 0x81 || len < 4)
1071 log_error ("invalid response header from PC/SC received\n");
1072 goto command_failed;
1074 len -= 4; /* Already read the error code. */
1075 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1076 | (msgbuf[7] << 8 ) | msgbuf[8]);
1077 if (err)
1079 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1080 pcsc_error_string (err), err);
1081 return pcsc_error_to_sw (err);
1084 full_len = len;
1086 n = *buflen < len ? *buflen : len;
1087 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1089 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1090 i? strerror (errno) : "premature EOF");
1091 goto command_failed;
1093 *buflen = n;
1095 full_len -= len;
1096 if (full_len)
1098 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1099 err = SW_HOST_INV_VALUE;
1101 /* We need to read any rest of the response, to keep the
1102 protocol running. */
1103 while (full_len)
1105 unsigned char dummybuf[128];
1107 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1108 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1110 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1111 i? strerror (errno) : "premature EOF");
1112 goto command_failed;
1114 full_len -= n;
1117 return err;
1119 command_failed:
1120 close (slotp->pcsc.req_fd);
1121 close (slotp->pcsc.rsp_fd);
1122 slotp->pcsc.req_fd = -1;
1123 slotp->pcsc.rsp_fd = -1;
1124 kill (slotp->pcsc.pid, SIGTERM);
1125 slotp->pcsc.pid = (pid_t)(-1);
1126 slotp->used = 0;
1127 return sw;
1129 #endif /*NEED_PCSC_WRAPPER*/
1132 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1133 *BUFLEN data in BUFFER, the actual returned size will be stored at
1134 BUFLEN. Returns: A status word. */
1135 static int
1136 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1137 unsigned char *buffer, size_t *buflen,
1138 struct pininfo_s *pininfo)
1140 #ifdef NEED_PCSC_WRAPPER
1141 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1142 #else
1143 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1144 #endif
1148 #ifndef NEED_PCSC_WRAPPER
1149 static int
1150 close_pcsc_reader_direct (int slot)
1152 pcsc_release_context (reader_table[slot].pcsc.context);
1153 xfree (reader_table[slot].rdrname);
1154 reader_table[slot].rdrname = NULL;
1155 reader_table[slot].used = 0;
1156 return 0;
1158 #endif /*!NEED_PCSC_WRAPPER*/
1161 #ifdef NEED_PCSC_WRAPPER
1162 static int
1163 close_pcsc_reader_wrapped (int slot)
1165 long err;
1166 reader_table_t slotp;
1167 size_t len;
1168 int i;
1169 unsigned char msgbuf[9];
1171 slotp = reader_table + slot;
1173 if (slotp->pcsc.req_fd == -1
1174 || slotp->pcsc.rsp_fd == -1
1175 || slotp->pcsc.pid == (pid_t)(-1) )
1177 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1178 return 0;
1181 msgbuf[0] = 0x02; /* CLOSE command. */
1182 len = 0;
1183 msgbuf[1] = (len >> 24);
1184 msgbuf[2] = (len >> 16);
1185 msgbuf[3] = (len >> 8);
1186 msgbuf[4] = (len );
1187 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1189 log_error ("error sending PC/SC CLOSE request: %s\n",
1190 strerror (errno));
1191 goto command_failed;
1194 /* Read the response. */
1195 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1197 log_error ("error receiving PC/SC CLOSE response: %s\n",
1198 i? strerror (errno) : "premature EOF");
1199 goto command_failed;
1201 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1202 if (msgbuf[0] != 0x81 || len < 4)
1204 log_error ("invalid response header from PC/SC received\n");
1205 goto command_failed;
1207 len -= 4; /* Already read the error code. */
1208 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1209 | (msgbuf[7] << 8 ) | msgbuf[8]);
1210 if (err)
1211 log_error ("pcsc_close failed: %s (0x%lx)\n",
1212 pcsc_error_string (err), err);
1214 /* We will close the wrapper in any case - errors are merely
1215 informational. */
1217 command_failed:
1218 close (slotp->pcsc.req_fd);
1219 close (slotp->pcsc.rsp_fd);
1220 slotp->pcsc.req_fd = -1;
1221 slotp->pcsc.rsp_fd = -1;
1222 kill (slotp->pcsc.pid, SIGTERM);
1223 slotp->pcsc.pid = (pid_t)(-1);
1224 slotp->used = 0;
1225 return 0;
1227 #endif /*NEED_PCSC_WRAPPER*/
1230 static int
1231 close_pcsc_reader (int slot)
1233 #ifdef NEED_PCSC_WRAPPER
1234 return close_pcsc_reader_wrapped (slot);
1235 #else
1236 return close_pcsc_reader_direct (slot);
1237 #endif
1241 /* Connect a PC/SC card. */
1242 #ifndef NEED_PCSC_WRAPPER
1243 static int
1244 connect_pcsc_card (int slot)
1246 long err;
1248 assert (slot >= 0 && slot < MAX_READER);
1250 if (reader_table[slot].pcsc.card)
1251 return SW_HOST_ALREADY_CONNECTED;
1253 reader_table[slot].atrlen = 0;
1254 reader_table[slot].last_status = 0;
1255 reader_table[slot].is_t0 = 0;
1257 err = pcsc_connect (reader_table[slot].pcsc.context,
1258 reader_table[slot].rdrname,
1259 PCSC_SHARE_EXCLUSIVE,
1260 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1261 &reader_table[slot].pcsc.card,
1262 &reader_table[slot].pcsc.protocol);
1263 if (err)
1265 reader_table[slot].pcsc.card = 0;
1266 if (err != PCSC_E_NO_SMARTCARD)
1267 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1268 pcsc_error_string (err), err);
1270 else
1272 char reader[250];
1273 unsigned long readerlen, atrlen;
1274 unsigned long card_state, card_protocol;
1276 atrlen = DIM (reader_table[0].atr);
1277 readerlen = sizeof reader -1 ;
1278 err = pcsc_status (reader_table[slot].pcsc.card,
1279 reader, &readerlen,
1280 &card_state, &card_protocol,
1281 reader_table[slot].atr, &atrlen);
1282 if (err)
1283 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1284 pcsc_error_string (err), err, readerlen);
1285 else
1287 if (atrlen > DIM (reader_table[0].atr))
1288 log_bug ("ATR returned by pcsc_status is too large\n");
1289 reader_table[slot].atrlen = atrlen;
1290 /* If we got to here we know that a card is present
1291 and usable. Remember this. */
1292 reader_table[slot].last_status = ( APDU_CARD_USABLE
1293 | APDU_CARD_PRESENT
1294 | APDU_CARD_ACTIVE);
1295 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1299 dump_reader_status (slot);
1300 return pcsc_error_to_sw (err);
1302 #endif /*!NEED_PCSC_WRAPPER*/
1305 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1306 is not connected. */
1307 #ifndef NEED_PCSC_WRAPPER
1308 static int
1309 disconnect_pcsc_card (int slot)
1311 long err;
1313 assert (slot >= 0 && slot < MAX_READER);
1315 if (!reader_table[slot].pcsc.card)
1316 return 0;
1318 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1319 if (err)
1321 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1322 pcsc_error_string (err), err);
1323 return SW_HOST_CARD_IO_ERROR;
1325 reader_table[slot].pcsc.card = 0;
1326 return 0;
1328 #endif /*!NEED_PCSC_WRAPPER*/
1331 #ifndef NEED_PCSC_WRAPPER
1332 static int
1333 reset_pcsc_reader_direct (int slot)
1335 int sw;
1337 sw = disconnect_pcsc_card (slot);
1338 if (!sw)
1339 sw = connect_pcsc_card (slot);
1341 return sw;
1343 #endif /*NEED_PCSC_WRAPPER*/
1346 #ifdef NEED_PCSC_WRAPPER
1347 static int
1348 reset_pcsc_reader_wrapped (int slot)
1350 long err;
1351 reader_table_t slotp;
1352 size_t len;
1353 int i, n;
1354 unsigned char msgbuf[9];
1355 unsigned int dummy_status;
1356 int sw = SW_HOST_CARD_IO_ERROR;
1358 slotp = reader_table + slot;
1360 if (slotp->pcsc.req_fd == -1
1361 || slotp->pcsc.rsp_fd == -1
1362 || slotp->pcsc.pid == (pid_t)(-1) )
1364 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1365 return sw;
1368 msgbuf[0] = 0x05; /* RESET command. */
1369 len = 0;
1370 msgbuf[1] = (len >> 24);
1371 msgbuf[2] = (len >> 16);
1372 msgbuf[3] = (len >> 8);
1373 msgbuf[4] = (len );
1374 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1376 log_error ("error sending PC/SC RESET request: %s\n",
1377 strerror (errno));
1378 goto command_failed;
1381 /* Read the response. */
1382 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1384 log_error ("error receiving PC/SC RESET response: %s\n",
1385 i? strerror (errno) : "premature EOF");
1386 goto command_failed;
1388 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1389 if (msgbuf[0] != 0x81 || len < 4)
1391 log_error ("invalid response header from PC/SC received\n");
1392 goto command_failed;
1394 len -= 4; /* Already read the error code. */
1395 if (len > DIM (slotp->atr))
1397 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1398 (unsigned long)len);
1399 sw = SW_HOST_GENERAL_ERROR;
1400 goto command_failed;
1402 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1403 | (msgbuf[7] << 8 ) | msgbuf[8]);
1404 if (err)
1406 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1407 pcsc_error_string (err), err);
1408 /* If the error code is no smart card, we should not considere
1409 this a major error and close the wrapper. */
1410 sw = pcsc_error_to_sw (err);
1411 if (err == PCSC_E_NO_SMARTCARD)
1412 return sw;
1413 goto command_failed;
1416 /* The open function may return a zero for the ATR length to
1417 indicate that no card is present. */
1418 n = len;
1419 if (n)
1421 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1423 log_error ("error receiving PC/SC RESET response: %s\n",
1424 i? strerror (errno) : "premature EOF");
1425 goto command_failed;
1428 slotp->atrlen = len;
1430 /* Read the status so that IS_T0 will be set. */
1431 pcsc_get_status (slot, &dummy_status);
1433 return 0;
1435 command_failed:
1436 close (slotp->pcsc.req_fd);
1437 close (slotp->pcsc.rsp_fd);
1438 slotp->pcsc.req_fd = -1;
1439 slotp->pcsc.rsp_fd = -1;
1440 kill (slotp->pcsc.pid, SIGTERM);
1441 slotp->pcsc.pid = (pid_t)(-1);
1442 slotp->used = 0;
1443 return sw;
1445 #endif /* !NEED_PCSC_WRAPPER */
1448 /* Send an PC/SC reset command and return a status word on error or 0
1449 on success. */
1450 static int
1451 reset_pcsc_reader (int slot)
1453 #ifdef NEED_PCSC_WRAPPER
1454 return reset_pcsc_reader_wrapped (slot);
1455 #else
1456 return reset_pcsc_reader_direct (slot);
1457 #endif
1461 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1462 error or a slot number for the reader. */
1463 #ifndef NEED_PCSC_WRAPPER
1464 static int
1465 open_pcsc_reader_direct (const char *portstr)
1467 long err;
1468 int slot;
1469 char *list = NULL;
1470 unsigned long nreader, listlen;
1471 char *p;
1473 slot = new_reader_slot ();
1474 if (slot == -1)
1475 return -1;
1477 /* Fixme: Allocating a context for each slot is not required. One
1478 global context should be sufficient. */
1479 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1480 &reader_table[slot].pcsc.context);
1481 if (err)
1483 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1484 pcsc_error_string (err), err);
1485 reader_table[slot].used = 0;
1486 return -1;
1489 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1490 NULL, NULL, &nreader);
1491 if (!err)
1493 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1494 if (!list)
1496 log_error ("error allocating memory for reader list\n");
1497 pcsc_release_context (reader_table[slot].pcsc.context);
1498 reader_table[slot].used = 0;
1499 return -1 /*SW_HOST_OUT_OF_CORE*/;
1501 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1502 NULL, list, &nreader);
1504 if (err)
1506 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1507 pcsc_error_string (err), err);
1508 pcsc_release_context (reader_table[slot].pcsc.context);
1509 reader_table[slot].used = 0;
1510 xfree (list);
1511 return -1;
1514 listlen = nreader;
1515 p = list;
1516 while (nreader)
1518 if (!*p && !p[1])
1519 break;
1520 if (*p)
1521 log_info ("detected reader `%s'\n", p);
1522 if (nreader < (strlen (p)+1))
1524 log_error ("invalid response from pcsc_list_readers\n");
1525 break;
1527 nreader -= strlen (p)+1;
1528 p += strlen (p) + 1;
1531 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1532 if (!reader_table[slot].rdrname)
1534 log_error ("error allocating memory for reader name\n");
1535 pcsc_release_context (reader_table[slot].pcsc.context);
1536 reader_table[slot].used = 0;
1537 return -1;
1539 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1540 xfree (list);
1541 list = NULL;
1543 reader_table[slot].pcsc.card = 0;
1544 reader_table[slot].atrlen = 0;
1545 reader_table[slot].last_status = 0;
1547 reader_table[slot].connect_card = connect_pcsc_card;
1548 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1549 reader_table[slot].close_reader = close_pcsc_reader;
1550 reader_table[slot].reset_reader = reset_pcsc_reader;
1551 reader_table[slot].get_status_reader = pcsc_get_status;
1552 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1553 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1555 dump_reader_status (slot);
1556 return slot;
1558 #endif /*!NEED_PCSC_WRAPPER */
1561 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1562 needed to cope with different thread models and other peculiarities
1563 of libpcsclite. */
1564 #ifdef NEED_PCSC_WRAPPER
1565 static int
1566 open_pcsc_reader_wrapped (const char *portstr)
1568 int slot;
1569 reader_table_t slotp;
1570 int fd, rp[2], wp[2];
1571 int n, i;
1572 pid_t pid;
1573 size_t len;
1574 unsigned char msgbuf[9];
1575 int err;
1576 unsigned int dummy_status;
1577 int sw = SW_HOST_CARD_IO_ERROR;
1578 /* Note that we use the constant and not the fucntion because this
1579 code won't be be used under Windows. */
1580 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1582 if (access (wrapperpgm, X_OK))
1584 log_error ("can't run PC/SC access module `%s': %s\n",
1585 wrapperpgm, strerror (errno));
1586 return -1;
1589 slot = new_reader_slot ();
1590 if (slot == -1)
1591 return -1;
1592 slotp = reader_table + slot;
1594 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
1595 the common directy but implement it directly so that this file
1596 may still be source copied. */
1598 if (pipe (rp) == -1)
1600 log_error ("error creating a pipe: %s\n", strerror (errno));
1601 slotp->used = 0;
1602 return -1;
1604 if (pipe (wp) == -1)
1606 log_error ("error creating a pipe: %s\n", strerror (errno));
1607 close (rp[0]);
1608 close (rp[1]);
1609 slotp->used = 0;
1610 return -1;
1613 pid = fork ();
1614 if (pid == -1)
1616 log_error ("error forking process: %s\n", strerror (errno));
1617 close (rp[0]);
1618 close (rp[1]);
1619 close (wp[0]);
1620 close (wp[1]);
1621 slotp->used = 0;
1622 return -1;
1624 slotp->pcsc.pid = pid;
1626 if (!pid)
1627 { /*
1628 === Child ===
1631 /* Double fork. */
1632 pid = fork ();
1633 if (pid == -1)
1634 _exit (31);
1635 if (pid)
1636 _exit (0); /* Immediate exit this parent, so that the child
1637 gets cleaned up by the init process. */
1639 /* Connect our pipes. */
1640 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1641 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1642 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1643 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1645 /* Send stderr to the bit bucket. */
1646 fd = open ("/dev/null", O_WRONLY);
1647 if (fd == -1)
1648 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1649 if (fd != 2 && dup2 (fd, 2) == -1)
1650 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1652 /* Close all other files. */
1653 close_all_fds (3, NULL);
1655 execl (wrapperpgm,
1656 "pcsc-wrapper",
1657 "--",
1658 "1", /* API version */
1659 opt.pcsc_driver, /* Name of the PC/SC library. */
1660 NULL);
1661 _exit (31);
1665 === Parent ===
1667 close (wp[0]);
1668 close (rp[1]);
1669 slotp->pcsc.req_fd = wp[1];
1670 slotp->pcsc.rsp_fd = rp[0];
1672 /* Wait for the intermediate child to terminate. */
1673 #ifdef USE_GNU_PTH
1674 #define WAIT pth_waitpid
1675 #else
1676 #define WAIT waitpid
1677 #endif
1678 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1680 #undef WAIT
1682 /* Now send the open request. */
1683 msgbuf[0] = 0x01; /* OPEN command. */
1684 len = portstr? strlen (portstr):0;
1685 msgbuf[1] = (len >> 24);
1686 msgbuf[2] = (len >> 16);
1687 msgbuf[3] = (len >> 8);
1688 msgbuf[4] = (len );
1689 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1690 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1692 log_error ("error sending PC/SC OPEN request: %s\n",
1693 strerror (errno));
1694 goto command_failed;
1696 /* Read the response. */
1697 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1699 log_error ("error receiving PC/SC OPEN response: %s\n",
1700 i? strerror (errno) : "premature EOF");
1701 goto command_failed;
1703 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1704 if (msgbuf[0] != 0x81 || len < 4)
1706 log_error ("invalid response header from PC/SC received\n");
1707 goto command_failed;
1709 len -= 4; /* Already read the error code. */
1710 if (len > DIM (slotp->atr))
1712 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1713 (unsigned long)len);
1714 goto command_failed;
1716 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1717 | (msgbuf[7] << 8 ) | msgbuf[8]);
1718 if (err)
1720 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1721 sw = pcsc_error_to_sw (err);
1722 goto command_failed;
1725 slotp->last_status = 0;
1727 /* The open request may return a zero for the ATR length to
1728 indicate that no card is present. */
1729 n = len;
1730 if (n)
1732 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1734 log_error ("error receiving PC/SC OPEN response: %s\n",
1735 i? strerror (errno) : "premature EOF");
1736 goto command_failed;
1738 /* If we got to here we know that a card is present
1739 and usable. Thus remember this. */
1740 slotp->last_status = ( APDU_CARD_USABLE
1741 | APDU_CARD_PRESENT
1742 | APDU_CARD_ACTIVE);
1744 slotp->atrlen = len;
1746 reader_table[slot].close_reader = close_pcsc_reader;
1747 reader_table[slot].reset_reader = reset_pcsc_reader;
1748 reader_table[slot].get_status_reader = pcsc_get_status;
1749 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1750 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1752 /* Read the status so that IS_T0 will be set. */
1753 pcsc_get_status (slot, &dummy_status);
1755 dump_reader_status (slot);
1756 return slot;
1758 command_failed:
1759 close (slotp->pcsc.req_fd);
1760 close (slotp->pcsc.rsp_fd);
1761 slotp->pcsc.req_fd = -1;
1762 slotp->pcsc.rsp_fd = -1;
1763 kill (slotp->pcsc.pid, SIGTERM);
1764 slotp->pcsc.pid = (pid_t)(-1);
1765 slotp->used = 0;
1766 /* There is no way to return SW. */
1767 return -1;
1770 #endif /*NEED_PCSC_WRAPPER*/
1773 static int
1774 open_pcsc_reader (const char *portstr)
1776 #ifdef NEED_PCSC_WRAPPER
1777 return open_pcsc_reader_wrapped (portstr);
1778 #else
1779 return open_pcsc_reader_direct (portstr);
1780 #endif
1785 #ifdef HAVE_LIBUSB
1787 Internal CCID driver interface.
1791 static void
1792 dump_ccid_reader_status (int slot)
1794 log_info ("reader slot %d: using ccid driver\n", slot);
1797 static int
1798 close_ccid_reader (int slot)
1800 ccid_close_reader (reader_table[slot].ccid.handle);
1801 reader_table[slot].used = 0;
1802 return 0;
1806 static int
1807 shutdown_ccid_reader (int slot)
1809 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1810 return 0;
1814 static int
1815 reset_ccid_reader (int slot)
1817 int err;
1818 reader_table_t slotp = reader_table + slot;
1819 unsigned char atr[33];
1820 size_t atrlen;
1822 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1823 if (err)
1824 return err;
1825 /* If the reset was successful, update the ATR. */
1826 assert (sizeof slotp->atr >= sizeof atr);
1827 slotp->atrlen = atrlen;
1828 memcpy (slotp->atr, atr, atrlen);
1829 dump_reader_status (slot);
1830 return 0;
1834 static int
1835 get_status_ccid (int slot, unsigned int *status)
1837 int rc;
1838 int bits;
1840 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1841 if (rc)
1842 return -1;
1844 if (bits == 0)
1845 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1846 else if (bits == 1)
1847 *status = APDU_CARD_PRESENT;
1848 else
1849 *status = 0;
1851 return 0;
1855 /* Actually send the APDU of length APDULEN to SLOT and return a
1856 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1857 set to BUFLEN. Returns: Internal CCID driver error code. */
1858 static int
1859 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1860 unsigned char *buffer, size_t *buflen,
1861 struct pininfo_s *pininfo)
1863 long err;
1864 size_t maxbuflen;
1866 /* If we don't have an ATR, we need to reset the reader first. */
1867 if (!reader_table[slot].atrlen
1868 && (err = reset_ccid_reader (slot)))
1869 return err;
1871 if (DBG_CARD_IO)
1872 log_printhex (" APDU_data:", apdu, apdulen);
1874 maxbuflen = *buflen;
1875 if (pininfo)
1876 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1877 apdu, apdulen,
1878 pininfo->mode,
1879 pininfo->minlen,
1880 pininfo->maxlen,
1881 pininfo->padlen,
1882 buffer, maxbuflen, buflen);
1883 else
1884 err = ccid_transceive (reader_table[slot].ccid.handle,
1885 apdu, apdulen,
1886 buffer, maxbuflen, buflen);
1887 if (err)
1888 log_error ("ccid_transceive failed: (0x%lx)\n",
1889 err);
1891 return err;
1895 /* Check whether the CCID reader supports the ISO command code COMMAND
1896 on the keypad. Return 0 on success. For a description of the pin
1897 parameters, see ccid-driver.c */
1898 static int
1899 check_ccid_keypad (int slot, int command, int pin_mode,
1900 int pinlen_min, int pinlen_max, int pin_padlen)
1902 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1904 apdu[1] = command;
1905 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1906 apdu, sizeof apdu,
1907 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1908 NULL, 0, NULL);
1912 /* Open the reader and try to read an ATR. */
1913 static int
1914 open_ccid_reader (const char *portstr)
1916 int err;
1917 int slot;
1918 reader_table_t slotp;
1920 slot = new_reader_slot ();
1921 if (slot == -1)
1922 return -1;
1923 slotp = reader_table + slot;
1925 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1926 if (err)
1928 slotp->used = 0;
1929 return -1;
1932 err = ccid_get_atr (slotp->ccid.handle,
1933 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1934 if (err)
1936 slotp->atrlen = 0;
1937 err = 0;
1939 else
1941 /* If we got to here we know that a card is present
1942 and usable. Thus remember this. */
1943 reader_table[slot].last_status = (APDU_CARD_USABLE
1944 | APDU_CARD_PRESENT
1945 | APDU_CARD_ACTIVE);
1948 reader_table[slot].close_reader = close_ccid_reader;
1949 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1950 reader_table[slot].reset_reader = reset_ccid_reader;
1951 reader_table[slot].get_status_reader = get_status_ccid;
1952 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1953 reader_table[slot].check_keypad = check_ccid_keypad;
1954 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1955 /* Our CCID reader code does not support T=0 at all, thus reset the
1956 flag. */
1957 reader_table[slot].is_t0 = 0;
1959 dump_reader_status (slot);
1960 return slot;
1965 #endif /* HAVE_LIBUSB */
1969 #ifdef USE_G10CODE_RAPDU
1971 The Remote APDU Interface.
1973 This uses the Remote APDU protocol to contact a reader.
1975 The port number is actually an index into the list of ports as
1976 returned via the protocol.
1980 static int
1981 rapdu_status_to_sw (int status)
1983 int rc;
1985 switch (status)
1987 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1989 case RAPDU_STATUS_INVCMD:
1990 case RAPDU_STATUS_INVPROT:
1991 case RAPDU_STATUS_INVSEQ:
1992 case RAPDU_STATUS_INVCOOKIE:
1993 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1995 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1996 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1997 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1998 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1999 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2000 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2002 default: rc = SW_HOST_GENERAL_ERROR; break;
2005 return rc;
2010 static int
2011 close_rapdu_reader (int slot)
2013 rapdu_release (reader_table[slot].rapdu.handle);
2014 reader_table[slot].used = 0;
2015 return 0;
2019 static int
2020 reset_rapdu_reader (int slot)
2022 int err;
2023 reader_table_t slotp;
2024 rapdu_msg_t msg = NULL;
2026 slotp = reader_table + slot;
2028 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2029 if (err)
2031 log_error ("sending rapdu command RESET failed: %s\n",
2032 err < 0 ? strerror (errno): rapdu_strerror (err));
2033 rapdu_msg_release (msg);
2034 return rapdu_status_to_sw (err);
2036 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2037 if (err)
2039 log_error ("receiving rapdu message failed: %s\n",
2040 err < 0 ? strerror (errno): rapdu_strerror (err));
2041 rapdu_msg_release (msg);
2042 return rapdu_status_to_sw (err);
2044 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2046 int sw = rapdu_status_to_sw (msg->cmd);
2047 log_error ("rapdu command RESET failed: %s\n",
2048 rapdu_strerror (msg->cmd));
2049 rapdu_msg_release (msg);
2050 return sw;
2052 if (msg->datalen > DIM (slotp->atr))
2054 log_error ("ATR returned by the RAPDU layer is too large\n");
2055 rapdu_msg_release (msg);
2056 return SW_HOST_INV_VALUE;
2058 slotp->atrlen = msg->datalen;
2059 memcpy (slotp->atr, msg->data, msg->datalen);
2061 rapdu_msg_release (msg);
2062 return 0;
2066 static int
2067 my_rapdu_get_status (int slot, unsigned int *status)
2069 int err;
2070 reader_table_t slotp;
2071 rapdu_msg_t msg = NULL;
2072 int oldslot;
2074 slotp = reader_table + slot;
2076 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2077 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2078 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2079 if (err)
2081 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2082 err < 0 ? strerror (errno): rapdu_strerror (err));
2083 return rapdu_status_to_sw (err);
2085 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2086 if (err)
2088 log_error ("receiving rapdu message failed: %s\n",
2089 err < 0 ? strerror (errno): rapdu_strerror (err));
2090 rapdu_msg_release (msg);
2091 return rapdu_status_to_sw (err);
2093 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2095 int sw = rapdu_status_to_sw (msg->cmd);
2096 log_error ("rapdu command GET_STATUS failed: %s\n",
2097 rapdu_strerror (msg->cmd));
2098 rapdu_msg_release (msg);
2099 return sw;
2101 *status = msg->data[0];
2103 rapdu_msg_release (msg);
2104 return 0;
2108 /* Actually send the APDU of length APDULEN to SLOT and return a
2109 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2110 set to BUFLEN. Returns: APDU error code. */
2111 static int
2112 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2113 unsigned char *buffer, size_t *buflen,
2114 struct pininfo_s *pininfo)
2116 int err;
2117 reader_table_t slotp;
2118 rapdu_msg_t msg = NULL;
2119 size_t maxlen = *buflen;
2121 slotp = reader_table + slot;
2123 *buflen = 0;
2124 if (DBG_CARD_IO)
2125 log_printhex (" APDU_data:", apdu, apdulen);
2127 if (apdulen < 4)
2129 log_error ("rapdu_send_apdu: APDU is too short\n");
2130 return SW_HOST_INV_VALUE;
2133 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2134 if (err)
2136 log_error ("sending rapdu command APDU failed: %s\n",
2137 err < 0 ? strerror (errno): rapdu_strerror (err));
2138 rapdu_msg_release (msg);
2139 return rapdu_status_to_sw (err);
2141 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2142 if (err)
2144 log_error ("receiving rapdu message failed: %s\n",
2145 err < 0 ? strerror (errno): rapdu_strerror (err));
2146 rapdu_msg_release (msg);
2147 return rapdu_status_to_sw (err);
2149 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2151 int sw = rapdu_status_to_sw (msg->cmd);
2152 log_error ("rapdu command APDU failed: %s\n",
2153 rapdu_strerror (msg->cmd));
2154 rapdu_msg_release (msg);
2155 return sw;
2158 if (msg->datalen > maxlen)
2160 log_error ("rapdu response apdu too large\n");
2161 rapdu_msg_release (msg);
2162 return SW_HOST_INV_VALUE;
2165 *buflen = msg->datalen;
2166 memcpy (buffer, msg->data, msg->datalen);
2168 rapdu_msg_release (msg);
2169 return 0;
2172 static int
2173 open_rapdu_reader (int portno,
2174 const unsigned char *cookie, size_t length,
2175 int (*readfnc) (void *opaque,
2176 void *buffer, size_t size),
2177 void *readfnc_value,
2178 int (*writefnc) (void *opaque,
2179 const void *buffer, size_t size),
2180 void *writefnc_value,
2181 void (*closefnc) (void *opaque),
2182 void *closefnc_value)
2184 int err;
2185 int slot;
2186 reader_table_t slotp;
2187 rapdu_msg_t msg = NULL;
2189 slot = new_reader_slot ();
2190 if (slot == -1)
2191 return -1;
2192 slotp = reader_table + slot;
2194 slotp->rapdu.handle = rapdu_new ();
2195 if (!slotp->rapdu.handle)
2197 slotp->used = 0;
2198 return -1;
2201 rapdu_set_reader (slotp->rapdu.handle, portno);
2203 rapdu_set_iofunc (slotp->rapdu.handle,
2204 readfnc, readfnc_value,
2205 writefnc, writefnc_value,
2206 closefnc, closefnc_value);
2207 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2209 /* First try to get the current ATR, but if the card is inactive
2210 issue a reset instead. */
2211 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2212 if (err == RAPDU_STATUS_NEEDRESET)
2213 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2214 if (err)
2216 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2217 err < 0 ? strerror (errno): rapdu_strerror (err));
2218 goto failure;
2220 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2221 if (err)
2223 log_info ("receiving rapdu message failed: %s\n",
2224 err < 0 ? strerror (errno): rapdu_strerror (err));
2225 goto failure;
2227 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2229 log_info ("rapdu command GET ATR failed: %s\n",
2230 rapdu_strerror (msg->cmd));
2231 goto failure;
2233 if (msg->datalen > DIM (slotp->atr))
2235 log_error ("ATR returned by the RAPDU layer is too large\n");
2236 goto failure;
2238 slotp->atrlen = msg->datalen;
2239 memcpy (slotp->atr, msg->data, msg->datalen);
2241 reader_table[slot].close_reader = close_rapdu_reader;
2242 reader_table[slot].reset_reader = reset_rapdu_reader;
2243 reader_table[slot].get_status_reader = my_rapdu_get_status;
2244 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2245 reader_table[slot].check_keypad = NULL;
2246 reader_table[slot].dump_status_reader = NULL;
2248 dump_reader_status (slot);
2249 rapdu_msg_release (msg);
2250 return slot;
2252 failure:
2253 rapdu_msg_release (msg);
2254 rapdu_release (slotp->rapdu.handle);
2255 slotp->used = 0;
2256 return -1;
2259 #endif /*USE_G10CODE_RAPDU*/
2264 Driver Access
2268 static int
2269 lock_slot (int slot)
2271 #ifdef USE_GNU_PTH
2272 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2274 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2275 return SW_HOST_LOCKING_FAILED;
2277 #endif /*USE_GNU_PTH*/
2278 return 0;
2281 static int
2282 trylock_slot (int slot)
2284 #ifdef USE_GNU_PTH
2285 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2287 if (errno == EBUSY)
2288 return SW_HOST_BUSY;
2289 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2290 return SW_HOST_LOCKING_FAILED;
2292 #endif /*USE_GNU_PTH*/
2293 return 0;
2296 static void
2297 unlock_slot (int slot)
2299 #ifdef USE_GNU_PTH
2300 if (!pth_mutex_release (&reader_table[slot].lock))
2301 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2302 #endif /*USE_GNU_PTH*/
2306 /* Open the reader and return an internal slot number or -1 on
2307 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2308 the first USB reader. For PC/SC the first listed reader). */
2310 apdu_open_reader (const char *portstr)
2312 static int pcsc_api_loaded, ct_api_loaded;
2314 #ifdef HAVE_LIBUSB
2315 if (!opt.disable_ccid)
2317 int slot, i;
2318 const char *s;
2320 slot = open_ccid_reader (portstr);
2321 if (slot != -1)
2322 return slot; /* got one */
2324 /* If a CCID reader specification has been given, the user does
2325 not want a fallback to other drivers. */
2326 if (portstr)
2327 for (s=portstr, i=0; *s; s++)
2328 if (*s == ':' && (++i == 3))
2329 return -1;
2332 #endif /* HAVE_LIBUSB */
2334 if (opt.ctapi_driver && *opt.ctapi_driver)
2336 int port = portstr? atoi (portstr) : 32768;
2338 if (!ct_api_loaded)
2340 void *handle;
2342 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2343 if (!handle)
2345 log_error ("apdu_open_reader: failed to open driver: %s\n",
2346 dlerror ());
2347 return -1;
2349 CT_init = dlsym (handle, "CT_init");
2350 CT_data = dlsym (handle, "CT_data");
2351 CT_close = dlsym (handle, "CT_close");
2352 if (!CT_init || !CT_data || !CT_close)
2354 log_error ("apdu_open_reader: invalid CT-API driver\n");
2355 dlclose (handle);
2356 return -1;
2358 ct_api_loaded = 1;
2360 return open_ct_reader (port);
2364 /* No ctAPI configured, so lets try the PC/SC API */
2365 if (!pcsc_api_loaded)
2367 #ifndef NEED_PCSC_WRAPPER
2368 void *handle;
2370 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2371 if (!handle)
2373 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2374 opt.pcsc_driver, dlerror ());
2375 return -1;
2378 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2379 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2380 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2381 #if defined(_WIN32) || defined(__CYGWIN__)
2382 if (!pcsc_list_readers)
2383 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2384 #endif
2385 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2386 #if defined(_WIN32) || defined(__CYGWIN__)
2387 if (!pcsc_get_status_change)
2388 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2389 #endif
2390 pcsc_connect = dlsym (handle, "SCardConnect");
2391 #if defined(_WIN32) || defined(__CYGWIN__)
2392 if (!pcsc_connect)
2393 pcsc_connect = dlsym (handle, "SCardConnectA");
2394 #endif
2395 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2396 #if defined(_WIN32) || defined(__CYGWIN__)
2397 if (!pcsc_reconnect)
2398 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2399 #endif
2400 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2401 pcsc_status = dlsym (handle, "SCardStatus");
2402 #if defined(_WIN32) || defined(__CYGWIN__)
2403 if (!pcsc_status)
2404 pcsc_status = dlsym (handle, "SCardStatusA");
2405 #endif
2406 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2407 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2408 pcsc_transmit = dlsym (handle, "SCardTransmit");
2409 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2411 if (!pcsc_establish_context
2412 || !pcsc_release_context
2413 || !pcsc_list_readers
2414 || !pcsc_get_status_change
2415 || !pcsc_connect
2416 || !pcsc_reconnect
2417 || !pcsc_disconnect
2418 || !pcsc_status
2419 || !pcsc_begin_transaction
2420 || !pcsc_end_transaction
2421 || !pcsc_transmit
2422 /* || !pcsc_set_timeout */)
2424 /* Note that set_timeout is currently not used and also not
2425 available under Windows. */
2426 log_error ("apdu_open_reader: invalid PC/SC driver "
2427 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2428 !!pcsc_establish_context,
2429 !!pcsc_release_context,
2430 !!pcsc_list_readers,
2431 !!pcsc_get_status_change,
2432 !!pcsc_connect,
2433 !!pcsc_reconnect,
2434 !!pcsc_disconnect,
2435 !!pcsc_status,
2436 !!pcsc_begin_transaction,
2437 !!pcsc_end_transaction,
2438 !!pcsc_transmit,
2439 !!pcsc_set_timeout );
2440 dlclose (handle);
2441 return -1;
2443 #endif /*!NEED_PCSC_WRAPPER*/
2444 pcsc_api_loaded = 1;
2447 return open_pcsc_reader (portstr);
2451 /* Open an remote reader and return an internal slot number or -1 on
2452 error. This function is an alternative to apdu_open_reader and used
2453 with remote readers only. Note that the supplied CLOSEFNC will
2454 only be called once and the slot will not be valid afther this.
2456 If PORTSTR is NULL we default to the first availabe port.
2459 apdu_open_remote_reader (const char *portstr,
2460 const unsigned char *cookie, size_t length,
2461 int (*readfnc) (void *opaque,
2462 void *buffer, size_t size),
2463 void *readfnc_value,
2464 int (*writefnc) (void *opaque,
2465 const void *buffer, size_t size),
2466 void *writefnc_value,
2467 void (*closefnc) (void *opaque),
2468 void *closefnc_value)
2470 #ifdef USE_G10CODE_RAPDU
2471 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2472 cookie, length,
2473 readfnc, readfnc_value,
2474 writefnc, writefnc_value,
2475 closefnc, closefnc_value);
2476 #else
2477 (void)portstr;
2478 (void)cookie;
2479 (void)length;
2480 (void)readfnc;
2481 (void)readfnc_value;
2482 (void)writefnc;
2483 (void)writefnc_value;
2484 (void)closefnc;
2485 (void)closefnc_value;
2486 #ifdef _WIN32
2487 errno = ENOENT;
2488 #else
2489 errno = ENOSYS;
2490 #endif
2491 return -1;
2492 #endif
2497 apdu_close_reader (int slot)
2499 int sw;
2501 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2502 return SW_HOST_NO_DRIVER;
2503 sw = apdu_disconnect (slot);
2504 if (sw)
2505 return sw;
2506 if (reader_table[slot].close_reader)
2507 return reader_table[slot].close_reader (slot);
2508 return SW_HOST_NOT_SUPPORTED;
2511 /* Shutdown a reader; that is basically the same as a close but keeps
2512 the handle ready for later use. A apdu_reset_reader or apdu_connect
2513 should be used to get it active again. */
2515 apdu_shutdown_reader (int slot)
2517 int sw;
2519 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2520 return SW_HOST_NO_DRIVER;
2521 sw = apdu_disconnect (slot);
2522 if (sw)
2523 return sw;
2524 if (reader_table[slot].shutdown_reader)
2525 return reader_table[slot].shutdown_reader (slot);
2526 return SW_HOST_NOT_SUPPORTED;
2529 /* Enumerate all readers and return information on whether this reader
2530 is in use. The caller should start with SLOT set to 0 and
2531 increment it with each call until an error is returned. */
2533 apdu_enum_reader (int slot, int *used)
2535 if (slot < 0 || slot >= MAX_READER)
2536 return SW_HOST_NO_DRIVER;
2537 *used = reader_table[slot].used;
2538 return 0;
2542 /* Connect a card. This is used to power up the card and make sure
2543 that an ATR is available. */
2545 apdu_connect (int slot)
2547 int sw;
2549 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2550 return SW_HOST_NO_DRIVER;
2552 /* Only if the access method provides a connect function we use it.
2553 If not, we expect that the card has been implicitly connected by
2554 apdu_open_reader. */
2555 if (reader_table[slot].connect_card)
2557 sw = lock_slot (slot);
2558 if (!sw)
2560 sw = reader_table[slot].connect_card (slot);
2561 unlock_slot (slot);
2564 else
2565 sw = 0;
2567 /* We need to call apdu_get_status_internal, so that the last-status
2568 machinery gets setup properly even if a card is inserted while
2569 scdaemon is fired up and apdu_get_status has not yet been called.
2570 Without that we would force a reset of the card with the next
2571 call to apdu_get_status. */
2572 apdu_get_status_internal (slot, 1, 1, NULL, NULL);
2574 return sw;
2579 apdu_disconnect (int slot)
2581 int sw;
2583 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2584 return SW_HOST_NO_DRIVER;
2586 if (reader_table[slot].disconnect_card)
2588 sw = lock_slot (slot);
2589 if (!sw)
2591 sw = reader_table[slot].disconnect_card (slot);
2592 unlock_slot (slot);
2595 else
2596 sw = 0;
2597 return sw;
2602 /* Do a reset for the card in reader at SLOT. */
2604 apdu_reset (int slot)
2606 int sw;
2608 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2609 return SW_HOST_NO_DRIVER;
2611 if ((sw = lock_slot (slot)))
2612 return sw;
2614 reader_table[slot].last_status = 0;
2615 if (reader_table[slot].reset_reader)
2616 sw = reader_table[slot].reset_reader (slot);
2618 if (!sw)
2620 /* If we got to here we know that a card is present
2621 and usable. Thus remember this. */
2622 reader_table[slot].last_status = (APDU_CARD_USABLE
2623 | APDU_CARD_PRESENT
2624 | APDU_CARD_ACTIVE);
2627 unlock_slot (slot);
2628 return sw;
2632 /* Activate a card if it has not yet been done. This is a kind of
2633 reset-if-required. It is useful to test for presence of a card
2634 before issuing a bunch of apdu commands. It does not wait on a
2635 locked card. */
2637 apdu_activate (int slot)
2639 int sw;
2640 unsigned int s;
2642 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2643 return SW_HOST_NO_DRIVER;
2645 if ((sw = trylock_slot (slot)))
2646 return sw;
2648 if (reader_table[slot].get_status_reader)
2649 sw = reader_table[slot].get_status_reader (slot, &s);
2651 if (!sw)
2653 if (!(s & 2)) /* Card not present. */
2654 sw = SW_HOST_NO_CARD;
2655 else if ( ((s & 2) && !(s & 4))
2656 || !reader_table[slot].atrlen )
2658 /* We don't have an ATR or a card is present though inactive:
2659 do a reset now. */
2660 if (reader_table[slot].reset_reader)
2662 reader_table[slot].last_status = 0;
2663 sw = reader_table[slot].reset_reader (slot);
2664 if (!sw)
2666 /* If we got to here we know that a card is present
2667 and usable. Thus remember this. */
2668 reader_table[slot].last_status = (APDU_CARD_USABLE
2669 | APDU_CARD_PRESENT
2670 | APDU_CARD_ACTIVE);
2676 unlock_slot (slot);
2677 return sw;
2682 unsigned char *
2683 apdu_get_atr (int slot, size_t *atrlen)
2685 unsigned char *buf;
2687 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2688 return NULL;
2689 if (!reader_table[slot].atrlen)
2690 return NULL;
2691 buf = xtrymalloc (reader_table[slot].atrlen);
2692 if (!buf)
2693 return NULL;
2694 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2695 *atrlen = reader_table[slot].atrlen;
2696 return buf;
2701 /* Retrieve the status for SLOT. The function does only wait for the
2702 card to become available if HANG is set to true. On success the
2703 bits in STATUS will be set to
2705 APDU_CARD_USABLE (bit 0) = card present and usable
2706 APDU_CARD_PRESENT (bit 1) = card present
2707 APDU_CARD_ACTIVE (bit 2) = card active
2708 (bit 3) = card access locked [not yet implemented]
2710 For must applications, testing bit 0 is sufficient.
2712 CHANGED will receive the value of the counter tracking the number
2713 of card insertions. This value may be used to detect a card
2714 change.
2716 static int
2717 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
2718 unsigned int *status, unsigned int *changed)
2720 int sw;
2721 unsigned int s;
2723 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2724 return SW_HOST_NO_DRIVER;
2726 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2727 return sw;
2729 if (reader_table[slot].get_status_reader)
2730 sw = reader_table[slot].get_status_reader (slot, &s);
2732 unlock_slot (slot);
2734 if (sw)
2736 reader_table[slot].last_status = 0;
2737 return sw;
2740 /* Keep track of changes. */
2741 if (s != reader_table[slot].last_status
2742 || !reader_table[slot].any_status )
2744 reader_table[slot].change_counter++;
2745 /* Make sure that the ATR is invalid so that a reset will be
2746 triggered by apdu_activate. */
2747 if (!no_atr_reset)
2748 reader_table[slot].atrlen = 0;
2750 reader_table[slot].any_status = 1;
2751 reader_table[slot].last_status = s;
2753 if (status)
2754 *status = s;
2755 if (changed)
2756 *changed = reader_table[slot].change_counter;
2757 return 0;
2761 /* See above for a description. */
2763 apdu_get_status (int slot, int hang,
2764 unsigned int *status, unsigned int *changed)
2766 return apdu_get_status_internal (slot, hang, 0, status, changed);
2770 /* Check whether the reader supports the ISO command code COMMAND on
2771 the keypad. Return 0 on success. For a description of the pin
2772 parameters, see ccid-driver.c */
2774 apdu_check_keypad (int slot, int command, int pin_mode,
2775 int pinlen_min, int pinlen_max, int pin_padlen)
2777 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2778 return SW_HOST_NO_DRIVER;
2780 if (reader_table[slot].check_keypad)
2781 return reader_table[slot].check_keypad (slot, command,
2782 pin_mode, pinlen_min, pinlen_max,
2783 pin_padlen);
2784 else
2785 return SW_HOST_NOT_SUPPORTED;
2789 /* Dispatcher for the actual send_apdu function. Note, that this
2790 function should be called in locked state. */
2791 static int
2792 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2793 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2795 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2796 return SW_HOST_NO_DRIVER;
2798 if (reader_table[slot].send_apdu_reader)
2799 return reader_table[slot].send_apdu_reader (slot,
2800 apdu, apdulen,
2801 buffer, buflen,
2802 pininfo);
2803 else
2804 return SW_HOST_NOT_SUPPORTED;
2808 /* Core APDU tranceiver function. Parameters are described at
2809 apdu_send_le with the exception of PININFO which indicates keypad
2810 related operations if not NULL. If EXTENDED_MODE is not 0
2811 command chaining or extended length will be used according to these
2812 values:
2813 n < 0 := Use command chaining with the data part limited to -n
2814 in each chunk. If -1 is used a default value is used.
2815 n == 0 := No extended mode or command chaining.
2816 n == 1 := Use extended length for input and output without a
2817 length limit.
2818 n > 1 := Use extended length with up to N bytes.
2820 FIXME: We don't support extended length return values larger
2821 than 256 bytes due to a static buffer.
2823 static int
2824 send_le (int slot, int class, int ins, int p0, int p1,
2825 int lc, const char *data, int le,
2826 unsigned char **retbuf, size_t *retbuflen,
2827 struct pininfo_s *pininfo, int extended_mode)
2829 #define RESULTLEN 258
2830 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2831 the driver. */
2832 size_t resultlen;
2833 unsigned char short_apdu_buffer[5+256+1];
2834 unsigned char *apdu_buffer = NULL;
2835 size_t apdu_buffer_size;
2836 unsigned char *apdu;
2837 size_t apdulen;
2838 int sw;
2839 long rc; /* We need a long here due to PC/SC. */
2840 int did_exact_length_hack = 0;
2841 int use_chaining = 0;
2842 int use_extended_length = 0;
2843 int lc_chunk;
2845 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2846 return SW_HOST_NO_DRIVER;
2848 if (DBG_CARD_IO)
2849 log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d em=%d\n",
2850 class, ins, p0, p1, lc, le, extended_mode);
2852 if (lc != -1 && (lc > 255 || lc < 0))
2854 /* Data does not fit into an APDU. What we do now depends on
2855 the EXTENDED_MODE parameter. */
2856 if (!extended_mode)
2857 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2858 else if (extended_mode > 0)
2859 use_extended_length = 1;
2860 else if (extended_mode < 0)
2862 /* Send APDU using chaining mode. */
2863 if (lc > 16384)
2864 return SW_WRONG_LENGTH; /* Sanity check. */
2865 if ((class&0xf0) != 0)
2866 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2867 use_chaining = extended_mode == -1? 255 : -extended_mode;
2868 use_chaining &= 0xff;
2870 else
2871 return SW_HOST_INV_VALUE;
2873 else if (lc == -1 && extended_mode > 0)
2874 use_extended_length = 1;
2876 if (le != -1 && (le > 256 || le < 0))
2877 return SW_WRONG_LENGTH;
2878 if ((!data && lc != -1) || (data && lc == -1))
2879 return SW_HOST_INV_VALUE;
2881 if (use_extended_length)
2883 if (reader_table[slot].is_t0)
2884 return SW_HOST_NOT_SUPPORTED;
2886 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2887 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2888 apdu_buffer = xtrymalloc (apdu_buffer_size);
2889 if (!apdu_buffer)
2890 return SW_HOST_OUT_OF_CORE;
2891 apdu = apdu_buffer;
2893 else
2895 apdu_buffer_size = sizeof short_apdu_buffer;
2896 apdu = short_apdu_buffer;
2899 if ((sw = lock_slot (slot)))
2900 return sw;
2904 if (use_extended_length)
2906 use_chaining = 0;
2907 apdulen = 0;
2908 apdu[apdulen++] = class;
2909 apdu[apdulen++] = ins;
2910 apdu[apdulen++] = p0;
2911 apdu[apdulen++] = p1;
2912 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
2913 if (lc >= 0)
2915 apdu[apdulen++] = ((lc >> 8) & 0xff);
2916 apdu[apdulen++] = (lc & 0xff);
2917 memcpy (apdu+apdulen, data, lc);
2918 data += lc;
2919 apdulen += lc;
2921 if (le != -1)
2923 apdu[apdulen++] = ((le >> 8) & 0xff);
2924 apdu[apdulen++] = (le & 0xff);
2927 else
2929 apdulen = 0;
2930 apdu[apdulen] = class;
2931 if (use_chaining && lc > 255)
2933 apdu[apdulen] |= 0x10;
2934 assert (use_chaining < 256);
2935 lc_chunk = use_chaining;
2936 lc -= use_chaining;
2938 else
2940 use_chaining = 0;
2941 lc_chunk = lc;
2943 apdulen++;
2944 apdu[apdulen++] = ins;
2945 apdu[apdulen++] = p0;
2946 apdu[apdulen++] = p1;
2947 if (lc_chunk != -1)
2949 apdu[apdulen++] = lc_chunk;
2950 memcpy (apdu+apdulen, data, lc_chunk);
2951 data += lc_chunk;
2952 apdulen += lc_chunk;
2953 /* T=0 does not allow the use of Lc together with Le;
2954 thus disable Le in this case. */
2955 if (reader_table[slot].is_t0)
2956 le = -1;
2958 if (le != -1 && !use_chaining)
2959 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
2962 exact_length_hack:
2963 /* As a safeguard don't pass any garbage to the driver. */
2964 assert (apdulen <= apdu_buffer_size);
2965 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
2966 resultlen = RESULTLEN;
2967 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2968 if (rc || resultlen < 2)
2970 log_error ("apdu_send_simple(%d) failed: %s\n",
2971 slot, apdu_strerror (rc));
2972 unlock_slot (slot);
2973 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2975 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2976 if (!use_extended_length
2977 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
2979 apdu[apdulen-1] = (sw & 0x00ff);
2980 did_exact_length_hack = 1;
2981 goto exact_length_hack;
2984 while (use_chaining && sw == SW_SUCCESS);
2986 if (apdu_buffer)
2988 xfree (apdu_buffer);
2989 apdu_buffer = NULL;
2990 apdu_buffer_size = 0;
2993 /* Store away the returned data but strip the statusword. */
2994 resultlen -= 2;
2995 if (DBG_CARD_IO)
2997 log_debug (" response: sw=%04X datalen=%d\n",
2998 sw, (unsigned int)resultlen);
2999 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3000 log_printhex (" dump: ", result, resultlen);
3003 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3005 if (retbuf)
3007 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3008 if (!*retbuf)
3010 unlock_slot (slot);
3011 return SW_HOST_OUT_OF_CORE;
3013 *retbuflen = resultlen;
3014 memcpy (*retbuf, result, resultlen);
3017 else if ((sw & 0xff00) == SW_MORE_DATA)
3019 unsigned char *p = NULL, *tmp;
3020 size_t bufsize = 4096;
3022 /* It is likely that we need to return much more data, so we
3023 start off with a large buffer. */
3024 if (retbuf)
3026 *retbuf = p = xtrymalloc (bufsize);
3027 if (!*retbuf)
3029 unlock_slot (slot);
3030 return SW_HOST_OUT_OF_CORE;
3032 assert (resultlen < bufsize);
3033 memcpy (p, result, resultlen);
3034 p += resultlen;
3039 int len = (sw & 0x00ff);
3041 if (DBG_CARD_IO)
3042 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3043 slot, len);
3044 apdu_buffer_size = sizeof short_apdu_buffer;
3045 apdu = short_apdu_buffer;
3046 apdulen = 0;
3047 apdu[apdulen++] = class;
3048 apdu[apdulen++] = 0xC0;
3049 apdu[apdulen++] = 0;
3050 apdu[apdulen++] = 0;
3051 apdu[apdulen++] = len;
3052 assert (apdulen <= apdu_buffer_size);
3053 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3054 resultlen = RESULTLEN;
3055 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3056 if (rc || resultlen < 2)
3058 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3059 slot, apdu_strerror (rc));
3060 unlock_slot (slot);
3061 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3063 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3064 resultlen -= 2;
3065 if (DBG_CARD_IO)
3067 log_debug (" more: sw=%04X datalen=%d\n",
3068 sw, (unsigned int)resultlen);
3069 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3070 log_printhex (" dump: ", result, resultlen);
3073 if ((sw & 0xff00) == SW_MORE_DATA
3074 || sw == SW_SUCCESS
3075 || sw == SW_EOF_REACHED )
3077 if (retbuf && resultlen)
3079 if (p - *retbuf + resultlen > bufsize)
3081 bufsize += resultlen > 4096? resultlen: 4096;
3082 tmp = xtryrealloc (*retbuf, bufsize);
3083 if (!tmp)
3085 unlock_slot (slot);
3086 return SW_HOST_OUT_OF_CORE;
3088 p = tmp + (p - *retbuf);
3089 *retbuf = tmp;
3091 memcpy (p, result, resultlen);
3092 p += resultlen;
3095 else
3096 log_info ("apdu_send_simple(%d) "
3097 "got unexpected status %04X from get response\n",
3098 slot, sw);
3100 while ((sw & 0xff00) == SW_MORE_DATA);
3102 if (retbuf)
3104 *retbuflen = p - *retbuf;
3105 tmp = xtryrealloc (*retbuf, *retbuflen);
3106 if (tmp)
3107 *retbuf = tmp;
3111 unlock_slot (slot);
3113 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3114 log_printhex (" dump: ", *retbuf, *retbuflen);
3116 return sw;
3117 #undef RESULTLEN
3120 /* Send an APDU to the card in SLOT. The APDU is created from all
3121 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
3122 for LC won't sent this field and the data field; in this case DATA
3123 must also be passed as NULL. If EXTENDED_MODE is not 0 command
3124 chaining or extended length will be used; see send_le for details.
3125 The return value is the status word or -1 for an invalid SLOT or
3126 other non card related error. If RETBUF is not NULL, it will
3127 receive an allocated buffer with the returned data. The length of
3128 that data will be put into *RETBUFLEN. The caller is reponsible
3129 for releasing the buffer even in case of errors. */
3131 apdu_send_le(int slot, int extended_mode,
3132 int class, int ins, int p0, int p1,
3133 int lc, const char *data, int le,
3134 unsigned char **retbuf, size_t *retbuflen)
3136 return send_le (slot, class, ins, p0, p1,
3137 lc, data, le,
3138 retbuf, retbuflen,
3139 NULL, extended_mode);
3143 /* Send an APDU to the card in SLOT. The APDU is created from all
3144 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3145 LC won't sent this field and the data field; in this case DATA must
3146 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3147 or extended length will be used; see send_le for details. The
3148 return value is the status word or -1 for an invalid SLOT or other
3149 non card related error. If RETBUF is not NULL, it will receive an
3150 allocated buffer with the returned data. The length of that data
3151 will be put into *RETBUFLEN. The caller is reponsible for
3152 releasing the buffer even in case of errors. */
3154 apdu_send (int slot, int extended_mode,
3155 int class, int ins, int p0, int p1,
3156 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
3158 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3159 retbuf, retbuflen, NULL, extended_mode);
3162 /* Send an APDU to the card in SLOT. The APDU is created from all
3163 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3164 LC won't sent this field and the data field; in this case DATA must
3165 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3166 or extended length will be used; see send_le for details. The
3167 return value is the status word or -1 for an invalid SLOT or other
3168 non card related error. No data will be returned. */
3170 apdu_send_simple (int slot, int extended_mode,
3171 int class, int ins, int p0, int p1,
3172 int lc, const char *data)
3174 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3175 extended_mode);
3179 /* Same as apdu_send_simple but uses the keypad of the reader. */
3181 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
3182 int lc, const char *data,
3183 int pin_mode,
3184 int pinlen_min, int pinlen_max, int pin_padlen)
3186 struct pininfo_s pininfo;
3188 pininfo.mode = pin_mode;
3189 pininfo.minlen = pinlen_min;
3190 pininfo.maxlen = pinlen_max;
3191 pininfo.padlen = pin_padlen;
3192 return send_le (slot, class, ins, p0, p1, lc, data, -1,
3193 NULL, NULL, &pininfo, 0);
3197 /* This is a more generic version of the apdu sending routine. It
3198 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3199 and returns with an APDU including the status word. With
3200 HANDLE_MORE set to true this function will handle the MORE DATA
3201 status and return all APDUs concatenated with one status word at
3202 the end. If EXTENDED_MODE is not 0 command chaining or extended
3203 length will be used; see send_le for details. The function does
3204 not return a regular status word but 0 on success. If the slot is
3205 locked, the function returns immediately with an error. */
3207 apdu_send_direct (int slot, int extended_mode,
3208 const unsigned char *apdudata, size_t apdudatalen,
3209 int handle_more,
3210 unsigned char **retbuf, size_t *retbuflen)
3212 #define RESULTLEN 258
3213 unsigned char apdu[5+256+1];
3214 size_t apdulen;
3215 unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
3216 the driver. */
3217 size_t resultlen;
3218 int sw;
3219 long rc; /* we need a long here due to PC/SC. */
3220 int class;
3222 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3223 return SW_HOST_NO_DRIVER;
3225 if (extended_mode)
3226 return SW_HOST_NOT_SUPPORTED; /* FIXME. */
3228 if ((sw = trylock_slot (slot)))
3229 return sw;
3231 /* We simply trunctate a too long APDU. */
3232 if (apdudatalen > sizeof apdu)
3233 apdudatalen = sizeof apdu;
3234 apdulen = apdudatalen;
3235 memcpy (apdu, apdudata, apdudatalen);
3236 class = apdulen? *apdu : 0;
3238 resultlen = RESULTLEN;
3239 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3240 if (rc || resultlen < 2)
3242 log_error ("apdu_send_direct(%d) failed: %s\n",
3243 slot, apdu_strerror (rc));
3244 unlock_slot (slot);
3245 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3247 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3248 /* Store away the returned data but strip the statusword. */
3249 resultlen -= 2;
3250 if (DBG_CARD_IO)
3252 log_debug (" response: sw=%04X datalen=%d\n",
3253 sw, (unsigned int)resultlen);
3254 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3255 log_printhex (" dump: ", result, resultlen);
3258 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3260 unsigned char *p = NULL, *tmp;
3261 size_t bufsize = 4096;
3263 /* It is likely that we need to return much more data, so we
3264 start off with a large buffer. */
3265 if (retbuf)
3267 *retbuf = p = xtrymalloc (bufsize + 2);
3268 if (!*retbuf)
3270 unlock_slot (slot);
3271 return SW_HOST_OUT_OF_CORE;
3273 assert (resultlen < bufsize);
3274 memcpy (p, result, resultlen);
3275 p += resultlen;
3280 int len = (sw & 0x00ff);
3282 if (DBG_CARD_IO)
3283 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3284 slot, len);
3285 apdulen = 0;
3286 apdu[apdulen++] = class;
3287 apdu[apdulen++] = 0xC0;
3288 apdu[apdulen++] = 0;
3289 apdu[apdulen++] = 0;
3290 apdu[apdulen++] = len;
3291 memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
3292 resultlen = RESULTLEN;
3293 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3294 if (rc || resultlen < 2)
3296 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3297 slot, apdu_strerror (rc));
3298 unlock_slot (slot);
3299 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3301 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3302 resultlen -= 2;
3303 if (DBG_CARD_IO)
3305 log_debug (" more: sw=%04X datalen=%d\n",
3306 sw, (unsigned int)resultlen);
3307 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3308 log_printhex (" dump: ", result, resultlen);
3311 if ((sw & 0xff00) == SW_MORE_DATA
3312 || sw == SW_SUCCESS
3313 || sw == SW_EOF_REACHED )
3315 if (retbuf && resultlen)
3317 if (p - *retbuf + resultlen > bufsize)
3319 bufsize += resultlen > 4096? resultlen: 4096;
3320 tmp = xtryrealloc (*retbuf, bufsize + 2);
3321 if (!tmp)
3323 unlock_slot (slot);
3324 return SW_HOST_OUT_OF_CORE;
3326 p = tmp + (p - *retbuf);
3327 *retbuf = tmp;
3329 memcpy (p, result, resultlen);
3330 p += resultlen;
3333 else
3334 log_info ("apdu_send_direct(%d) "
3335 "got unexpected status %04X from get response\n",
3336 slot, sw);
3338 while ((sw & 0xff00) == SW_MORE_DATA);
3340 if (retbuf)
3342 *retbuflen = p - *retbuf;
3343 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3344 if (tmp)
3345 *retbuf = tmp;
3348 else
3350 if (retbuf)
3352 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3353 if (!*retbuf)
3355 unlock_slot (slot);
3356 return SW_HOST_OUT_OF_CORE;
3358 *retbuflen = resultlen;
3359 memcpy (*retbuf, result, resultlen);
3363 unlock_slot (slot);
3365 /* Append the status word. Note that we reserved the two extra
3366 bytes while allocating the buffer. */
3367 if (retbuf)
3369 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3370 (*retbuf)[(*retbuflen)++] = sw;
3373 if (DBG_CARD_IO && retbuf)
3374 log_printhex (" dump: ", *retbuf, *retbuflen);
3376 return 0;
3377 #undef RESULTLEN