Better reset the PIN verification stati after changing the key attributes.
[gnupg.git] / scd / apdu.c
blob156c37eb8de3598e4ee71624b891d797153b0aa7
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 # ifdef HAVE_W32_SYSTEM
675 # error Cannot use pth_read here because it expects a system HANDLE.
676 # endif
677 n = pth_read (fd, buf, nleft);
678 #else
679 n = read (fd, buf, nleft);
680 #endif
681 if (n < 0 && errno == EINTR)
682 continue;
683 if (n < 0)
684 return -1; /* read error. */
685 if (!n)
686 break; /* EOF */
687 nleft -= n;
688 buf = (char*)buf + n;
690 if (nread)
691 *nread = buflen - nleft;
693 /* log_printhex (" readn:", orig_buf, *nread); */
695 return 0;
697 #endif /*NEED_PCSC_WRAPPER*/
699 static const char *
700 pcsc_error_string (long err)
702 const char *s;
704 if (!err)
705 return "okay";
706 if ((err & 0x80100000) != 0x80100000)
707 return "invalid PC/SC error code";
708 err &= 0xffff;
709 switch (err)
711 case 0x0002: s = "cancelled"; break;
712 case 0x000e: s = "can't dispose"; break;
713 case 0x0008: s = "insufficient buffer"; break;
714 case 0x0015: s = "invalid ATR"; break;
715 case 0x0003: s = "invalid handle"; break;
716 case 0x0004: s = "invalid parameter"; break;
717 case 0x0005: s = "invalid target"; break;
718 case 0x0011: s = "invalid value"; break;
719 case 0x0006: s = "no memory"; break;
720 case 0x0013: s = "comm error"; break;
721 case 0x0001: s = "internal error"; break;
722 case 0x0014: s = "unknown error"; break;
723 case 0x0007: s = "waited too long"; break;
724 case 0x0009: s = "unknown reader"; break;
725 case 0x000a: s = "timeout"; break;
726 case 0x000b: s = "sharing violation"; break;
727 case 0x000c: s = "no smartcard"; break;
728 case 0x000d: s = "unknown card"; break;
729 case 0x000f: s = "proto mismatch"; break;
730 case 0x0010: s = "not ready"; break;
731 case 0x0012: s = "system cancelled"; break;
732 case 0x0016: s = "not transacted"; break;
733 case 0x0017: s = "reader unavailable"; break;
734 case 0x0065: s = "unsupported card"; break;
735 case 0x0066: s = "unresponsive card"; break;
736 case 0x0067: s = "unpowered card"; break;
737 case 0x0068: s = "reset card"; break;
738 case 0x0069: s = "removed card"; break;
739 case 0x006a: s = "inserted card"; break;
740 case 0x001f: s = "unsupported feature"; break;
741 case 0x0019: s = "PCI too small"; break;
742 case 0x001a: s = "reader unsupported"; break;
743 case 0x001b: s = "duplicate reader"; break;
744 case 0x001c: s = "card unsupported"; break;
745 case 0x001d: s = "no service"; break;
746 case 0x001e: s = "service stopped"; break;
747 default: s = "unknown PC/SC error code"; break;
749 return s;
752 /* Map PC/SC error codes to our special host status words. */
753 static int
754 pcsc_error_to_sw (long ec)
756 int rc;
758 switch ( PCSC_ERR_MASK (ec) )
760 case 0: rc = 0; break;
762 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
763 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
764 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
765 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
766 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
767 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
769 case PCSC_E_INVALID_TARGET:
770 case PCSC_E_INVALID_VALUE:
771 case PCSC_E_INVALID_HANDLE:
772 case PCSC_E_INVALID_PARAMETER:
773 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
775 default: rc = SW_HOST_GENERAL_ERROR; break;
778 return rc;
781 static void
782 dump_pcsc_reader_status (int slot)
784 if (reader_table[slot].pcsc.card)
786 log_info ("reader slot %d: active protocol:", slot);
787 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
788 log_printf (" T0");
789 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
790 log_printf (" T1");
791 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
792 log_printf (" raw");
793 log_printf ("\n");
795 else
796 log_info ("reader slot %d: not connected\n", slot);
800 #ifndef NEED_PCSC_WRAPPER
801 static int
802 pcsc_get_status_direct (int slot, unsigned int *status)
804 long err;
805 struct pcsc_readerstate_s rdrstates[1];
807 memset (rdrstates, 0, sizeof *rdrstates);
808 rdrstates[0].reader = reader_table[slot].rdrname;
809 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
810 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
812 rdrstates, 1);
813 if (err == PCSC_E_TIMEOUT)
814 err = 0; /* Timeout is no error error here. */
815 if (err)
817 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
818 pcsc_error_string (err), err);
819 return pcsc_error_to_sw (err);
822 /* log_debug */
823 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
824 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
825 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
826 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
827 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
828 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
829 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
830 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
831 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
832 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
833 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
835 *status = 0;
836 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
837 *status |= APDU_CARD_PRESENT;
838 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
839 *status |= APDU_CARD_ACTIVE;
840 #ifndef HAVE_W32_SYSTEM
841 /* We indicate a useful card if it is not in use by another
842 application. This is because we only use exclusive access
843 mode. */
844 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
845 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
846 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
847 *status |= APDU_CARD_USABLE;
848 #else
849 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
850 time when we are the only user (SCM SCR335) under Windows. */
851 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
852 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
853 *status |= APDU_CARD_USABLE;
854 #endif
856 return 0;
858 #endif /*!NEED_PCSC_WRAPPER*/
861 #ifdef NEED_PCSC_WRAPPER
862 static int
863 pcsc_get_status_wrapped (int slot, unsigned int *status)
865 long err;
866 reader_table_t slotp;
867 size_t len, full_len;
868 int i, n;
869 unsigned char msgbuf[9];
870 unsigned char buffer[16];
871 int sw = SW_HOST_CARD_IO_ERROR;
873 slotp = reader_table + slot;
875 if (slotp->pcsc.req_fd == -1
876 || slotp->pcsc.rsp_fd == -1
877 || slotp->pcsc.pid == (pid_t)(-1) )
879 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
880 return sw;
883 msgbuf[0] = 0x04; /* STATUS command. */
884 len = 0;
885 msgbuf[1] = (len >> 24);
886 msgbuf[2] = (len >> 16);
887 msgbuf[3] = (len >> 8);
888 msgbuf[4] = (len );
889 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
891 log_error ("error sending PC/SC STATUS request: %s\n",
892 strerror (errno));
893 goto command_failed;
896 /* Read the response. */
897 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
899 log_error ("error receiving PC/SC STATUS response: %s\n",
900 i? strerror (errno) : "premature EOF");
901 goto command_failed;
903 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
904 if (msgbuf[0] != 0x81 || len < 4)
906 log_error ("invalid response header from PC/SC received\n");
907 goto command_failed;
909 len -= 4; /* Already read the error code. */
910 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
911 | (msgbuf[7] << 8 ) | msgbuf[8]);
912 if (err)
914 log_error ("pcsc_status failed: %s (0x%lx)\n",
915 pcsc_error_string (err), err);
916 /* This is a proper error code, so return immediately. */
917 return pcsc_error_to_sw (err);
920 full_len = len;
922 /* The current version returns 3 words but we allow also for old
923 versions returning only 2 words. */
924 n = 12 < len ? 12 : len;
925 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
926 || (len != 8 && len != 12))
928 log_error ("error receiving PC/SC STATUS response: %s\n",
929 i? strerror (errno) : "premature EOF");
930 goto command_failed;
933 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
936 full_len -= len;
937 /* Newer versions of the wrapper might send more status bytes.
938 Read them. */
939 while (full_len)
941 unsigned char dummybuf[128];
943 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
944 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
946 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
947 i? strerror (errno) : "premature EOF");
948 goto command_failed;
950 full_len -= n;
953 /* We are lucky: The wrapper already returns the data in the
954 required format. */
955 *status = buffer[3];
956 return 0;
958 command_failed:
959 close (slotp->pcsc.req_fd);
960 close (slotp->pcsc.rsp_fd);
961 slotp->pcsc.req_fd = -1;
962 slotp->pcsc.rsp_fd = -1;
963 kill (slotp->pcsc.pid, SIGTERM);
964 slotp->pcsc.pid = (pid_t)(-1);
965 slotp->used = 0;
966 return sw;
968 #endif /*NEED_PCSC_WRAPPER*/
971 static int
972 pcsc_get_status (int slot, unsigned int *status)
974 #ifdef NEED_PCSC_WRAPPER
975 return pcsc_get_status_wrapped (slot, status);
976 #else
977 return pcsc_get_status_direct (slot, status);
978 #endif
982 #ifndef NEED_PCSC_WRAPPER
983 static int
984 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
985 unsigned char *buffer, size_t *buflen,
986 struct pininfo_s *pininfo)
988 long err;
989 struct pcsc_io_request_s send_pci;
990 unsigned long recv_len;
992 if (!reader_table[slot].atrlen
993 && (err = reset_pcsc_reader (slot)))
994 return err;
996 if (DBG_CARD_IO)
997 log_printhex (" PCSC_data:", apdu, apdulen);
999 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1000 send_pci.protocol = PCSC_PROTOCOL_T1;
1001 else
1002 send_pci.protocol = PCSC_PROTOCOL_T0;
1003 send_pci.pci_len = sizeof send_pci;
1004 recv_len = *buflen;
1005 err = pcsc_transmit (reader_table[slot].pcsc.card,
1006 &send_pci, apdu, apdulen,
1007 NULL, buffer, &recv_len);
1008 *buflen = recv_len;
1009 if (err)
1010 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1011 pcsc_error_string (err), err);
1013 return pcsc_error_to_sw (err);
1015 #endif /*!NEED_PCSC_WRAPPER*/
1018 #ifdef NEED_PCSC_WRAPPER
1019 static int
1020 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1021 unsigned char *buffer, size_t *buflen,
1022 struct pininfo_s *pininfo)
1024 long err;
1025 reader_table_t slotp;
1026 size_t len, full_len;
1027 int i, n;
1028 unsigned char msgbuf[9];
1029 int sw = SW_HOST_CARD_IO_ERROR;
1031 (void)pininfo;
1033 if (!reader_table[slot].atrlen
1034 && (err = reset_pcsc_reader (slot)))
1035 return err;
1037 if (DBG_CARD_IO)
1038 log_printhex (" PCSC_data:", apdu, apdulen);
1040 slotp = reader_table + slot;
1042 if (slotp->pcsc.req_fd == -1
1043 || slotp->pcsc.rsp_fd == -1
1044 || slotp->pcsc.pid == (pid_t)(-1) )
1046 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1047 return sw;
1050 msgbuf[0] = 0x03; /* TRANSMIT command. */
1051 len = apdulen;
1052 msgbuf[1] = (len >> 24);
1053 msgbuf[2] = (len >> 16);
1054 msgbuf[3] = (len >> 8);
1055 msgbuf[4] = (len );
1056 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1057 || writen (slotp->pcsc.req_fd, apdu, len))
1059 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1060 strerror (errno));
1061 goto command_failed;
1064 /* Read the response. */
1065 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1067 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1068 i? strerror (errno) : "premature EOF");
1069 goto command_failed;
1071 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1072 if (msgbuf[0] != 0x81 || len < 4)
1074 log_error ("invalid response header from PC/SC received\n");
1075 goto command_failed;
1077 len -= 4; /* Already read the error code. */
1078 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1079 | (msgbuf[7] << 8 ) | msgbuf[8]);
1080 if (err)
1082 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1083 pcsc_error_string (err), err);
1084 return pcsc_error_to_sw (err);
1087 full_len = len;
1089 n = *buflen < len ? *buflen : len;
1090 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1092 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1093 i? strerror (errno) : "premature EOF");
1094 goto command_failed;
1096 *buflen = n;
1098 full_len -= len;
1099 if (full_len)
1101 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1102 err = SW_HOST_INV_VALUE;
1104 /* We need to read any rest of the response, to keep the
1105 protocol running. */
1106 while (full_len)
1108 unsigned char dummybuf[128];
1110 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1111 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1113 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1114 i? strerror (errno) : "premature EOF");
1115 goto command_failed;
1117 full_len -= n;
1120 return err;
1122 command_failed:
1123 close (slotp->pcsc.req_fd);
1124 close (slotp->pcsc.rsp_fd);
1125 slotp->pcsc.req_fd = -1;
1126 slotp->pcsc.rsp_fd = -1;
1127 kill (slotp->pcsc.pid, SIGTERM);
1128 slotp->pcsc.pid = (pid_t)(-1);
1129 slotp->used = 0;
1130 return sw;
1132 #endif /*NEED_PCSC_WRAPPER*/
1135 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1136 *BUFLEN data in BUFFER, the actual returned size will be stored at
1137 BUFLEN. Returns: A status word. */
1138 static int
1139 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1140 unsigned char *buffer, size_t *buflen,
1141 struct pininfo_s *pininfo)
1143 #ifdef NEED_PCSC_WRAPPER
1144 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1145 #else
1146 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1147 #endif
1151 #ifndef NEED_PCSC_WRAPPER
1152 static int
1153 close_pcsc_reader_direct (int slot)
1155 pcsc_release_context (reader_table[slot].pcsc.context);
1156 xfree (reader_table[slot].rdrname);
1157 reader_table[slot].rdrname = NULL;
1158 reader_table[slot].used = 0;
1159 return 0;
1161 #endif /*!NEED_PCSC_WRAPPER*/
1164 #ifdef NEED_PCSC_WRAPPER
1165 static int
1166 close_pcsc_reader_wrapped (int slot)
1168 long err;
1169 reader_table_t slotp;
1170 size_t len;
1171 int i;
1172 unsigned char msgbuf[9];
1174 slotp = reader_table + slot;
1176 if (slotp->pcsc.req_fd == -1
1177 || slotp->pcsc.rsp_fd == -1
1178 || slotp->pcsc.pid == (pid_t)(-1) )
1180 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1181 return 0;
1184 msgbuf[0] = 0x02; /* CLOSE command. */
1185 len = 0;
1186 msgbuf[1] = (len >> 24);
1187 msgbuf[2] = (len >> 16);
1188 msgbuf[3] = (len >> 8);
1189 msgbuf[4] = (len );
1190 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1192 log_error ("error sending PC/SC CLOSE request: %s\n",
1193 strerror (errno));
1194 goto command_failed;
1197 /* Read the response. */
1198 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1200 log_error ("error receiving PC/SC CLOSE response: %s\n",
1201 i? strerror (errno) : "premature EOF");
1202 goto command_failed;
1204 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1205 if (msgbuf[0] != 0x81 || len < 4)
1207 log_error ("invalid response header from PC/SC received\n");
1208 goto command_failed;
1210 len -= 4; /* Already read the error code. */
1211 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1212 | (msgbuf[7] << 8 ) | msgbuf[8]);
1213 if (err)
1214 log_error ("pcsc_close failed: %s (0x%lx)\n",
1215 pcsc_error_string (err), err);
1217 /* We will close the wrapper in any case - errors are merely
1218 informational. */
1220 command_failed:
1221 close (slotp->pcsc.req_fd);
1222 close (slotp->pcsc.rsp_fd);
1223 slotp->pcsc.req_fd = -1;
1224 slotp->pcsc.rsp_fd = -1;
1225 kill (slotp->pcsc.pid, SIGTERM);
1226 slotp->pcsc.pid = (pid_t)(-1);
1227 slotp->used = 0;
1228 return 0;
1230 #endif /*NEED_PCSC_WRAPPER*/
1233 static int
1234 close_pcsc_reader (int slot)
1236 #ifdef NEED_PCSC_WRAPPER
1237 return close_pcsc_reader_wrapped (slot);
1238 #else
1239 return close_pcsc_reader_direct (slot);
1240 #endif
1244 /* Connect a PC/SC card. */
1245 #ifndef NEED_PCSC_WRAPPER
1246 static int
1247 connect_pcsc_card (int slot)
1249 long err;
1251 assert (slot >= 0 && slot < MAX_READER);
1253 if (reader_table[slot].pcsc.card)
1254 return SW_HOST_ALREADY_CONNECTED;
1256 reader_table[slot].atrlen = 0;
1257 reader_table[slot].last_status = 0;
1258 reader_table[slot].is_t0 = 0;
1260 err = pcsc_connect (reader_table[slot].pcsc.context,
1261 reader_table[slot].rdrname,
1262 PCSC_SHARE_EXCLUSIVE,
1263 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1264 &reader_table[slot].pcsc.card,
1265 &reader_table[slot].pcsc.protocol);
1266 if (err)
1268 reader_table[slot].pcsc.card = 0;
1269 if (err != PCSC_E_NO_SMARTCARD)
1270 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1271 pcsc_error_string (err), err);
1273 else
1275 char reader[250];
1276 unsigned long readerlen, atrlen;
1277 unsigned long card_state, card_protocol;
1279 atrlen = DIM (reader_table[0].atr);
1280 readerlen = sizeof reader -1 ;
1281 err = pcsc_status (reader_table[slot].pcsc.card,
1282 reader, &readerlen,
1283 &card_state, &card_protocol,
1284 reader_table[slot].atr, &atrlen);
1285 if (err)
1286 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1287 pcsc_error_string (err), err, readerlen);
1288 else
1290 if (atrlen > DIM (reader_table[0].atr))
1291 log_bug ("ATR returned by pcsc_status is too large\n");
1292 reader_table[slot].atrlen = atrlen;
1293 /* If we got to here we know that a card is present
1294 and usable. Remember this. */
1295 reader_table[slot].last_status = ( APDU_CARD_USABLE
1296 | APDU_CARD_PRESENT
1297 | APDU_CARD_ACTIVE);
1298 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1302 dump_reader_status (slot);
1303 return pcsc_error_to_sw (err);
1305 #endif /*!NEED_PCSC_WRAPPER*/
1308 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1309 is not connected. */
1310 #ifndef NEED_PCSC_WRAPPER
1311 static int
1312 disconnect_pcsc_card (int slot)
1314 long err;
1316 assert (slot >= 0 && slot < MAX_READER);
1318 if (!reader_table[slot].pcsc.card)
1319 return 0;
1321 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1322 if (err)
1324 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1325 pcsc_error_string (err), err);
1326 return SW_HOST_CARD_IO_ERROR;
1328 reader_table[slot].pcsc.card = 0;
1329 return 0;
1331 #endif /*!NEED_PCSC_WRAPPER*/
1334 #ifndef NEED_PCSC_WRAPPER
1335 static int
1336 reset_pcsc_reader_direct (int slot)
1338 int sw;
1340 sw = disconnect_pcsc_card (slot);
1341 if (!sw)
1342 sw = connect_pcsc_card (slot);
1344 return sw;
1346 #endif /*NEED_PCSC_WRAPPER*/
1349 #ifdef NEED_PCSC_WRAPPER
1350 static int
1351 reset_pcsc_reader_wrapped (int slot)
1353 long err;
1354 reader_table_t slotp;
1355 size_t len;
1356 int i, n;
1357 unsigned char msgbuf[9];
1358 unsigned int dummy_status;
1359 int sw = SW_HOST_CARD_IO_ERROR;
1361 slotp = reader_table + slot;
1363 if (slotp->pcsc.req_fd == -1
1364 || slotp->pcsc.rsp_fd == -1
1365 || slotp->pcsc.pid == (pid_t)(-1) )
1367 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1368 return sw;
1371 msgbuf[0] = 0x05; /* RESET command. */
1372 len = 0;
1373 msgbuf[1] = (len >> 24);
1374 msgbuf[2] = (len >> 16);
1375 msgbuf[3] = (len >> 8);
1376 msgbuf[4] = (len );
1377 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1379 log_error ("error sending PC/SC RESET request: %s\n",
1380 strerror (errno));
1381 goto command_failed;
1384 /* Read the response. */
1385 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1387 log_error ("error receiving PC/SC RESET response: %s\n",
1388 i? strerror (errno) : "premature EOF");
1389 goto command_failed;
1391 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1392 if (msgbuf[0] != 0x81 || len < 4)
1394 log_error ("invalid response header from PC/SC received\n");
1395 goto command_failed;
1397 len -= 4; /* Already read the error code. */
1398 if (len > DIM (slotp->atr))
1400 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1401 (unsigned long)len);
1402 sw = SW_HOST_GENERAL_ERROR;
1403 goto command_failed;
1405 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1406 | (msgbuf[7] << 8 ) | msgbuf[8]);
1407 if (err)
1409 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1410 pcsc_error_string (err), err);
1411 /* If the error code is no smart card, we should not considere
1412 this a major error and close the wrapper. */
1413 sw = pcsc_error_to_sw (err);
1414 if (err == PCSC_E_NO_SMARTCARD)
1415 return sw;
1416 goto command_failed;
1419 /* The open function may return a zero for the ATR length to
1420 indicate that no card is present. */
1421 n = len;
1422 if (n)
1424 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1426 log_error ("error receiving PC/SC RESET response: %s\n",
1427 i? strerror (errno) : "premature EOF");
1428 goto command_failed;
1431 slotp->atrlen = len;
1433 /* Read the status so that IS_T0 will be set. */
1434 pcsc_get_status (slot, &dummy_status);
1436 return 0;
1438 command_failed:
1439 close (slotp->pcsc.req_fd);
1440 close (slotp->pcsc.rsp_fd);
1441 slotp->pcsc.req_fd = -1;
1442 slotp->pcsc.rsp_fd = -1;
1443 kill (slotp->pcsc.pid, SIGTERM);
1444 slotp->pcsc.pid = (pid_t)(-1);
1445 slotp->used = 0;
1446 return sw;
1448 #endif /* !NEED_PCSC_WRAPPER */
1451 /* Send an PC/SC reset command and return a status word on error or 0
1452 on success. */
1453 static int
1454 reset_pcsc_reader (int slot)
1456 #ifdef NEED_PCSC_WRAPPER
1457 return reset_pcsc_reader_wrapped (slot);
1458 #else
1459 return reset_pcsc_reader_direct (slot);
1460 #endif
1464 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1465 error or a slot number for the reader. */
1466 #ifndef NEED_PCSC_WRAPPER
1467 static int
1468 open_pcsc_reader_direct (const char *portstr)
1470 long err;
1471 int slot;
1472 char *list = NULL;
1473 unsigned long nreader, listlen;
1474 char *p;
1476 slot = new_reader_slot ();
1477 if (slot == -1)
1478 return -1;
1480 /* Fixme: Allocating a context for each slot is not required. One
1481 global context should be sufficient. */
1482 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1483 &reader_table[slot].pcsc.context);
1484 if (err)
1486 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1487 pcsc_error_string (err), err);
1488 reader_table[slot].used = 0;
1489 return -1;
1492 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1493 NULL, NULL, &nreader);
1494 if (!err)
1496 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1497 if (!list)
1499 log_error ("error allocating memory for reader list\n");
1500 pcsc_release_context (reader_table[slot].pcsc.context);
1501 reader_table[slot].used = 0;
1502 return -1 /*SW_HOST_OUT_OF_CORE*/;
1504 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1505 NULL, list, &nreader);
1507 if (err)
1509 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1510 pcsc_error_string (err), err);
1511 pcsc_release_context (reader_table[slot].pcsc.context);
1512 reader_table[slot].used = 0;
1513 xfree (list);
1514 return -1;
1517 listlen = nreader;
1518 p = list;
1519 while (nreader)
1521 if (!*p && !p[1])
1522 break;
1523 if (*p)
1524 log_info ("detected reader `%s'\n", p);
1525 if (nreader < (strlen (p)+1))
1527 log_error ("invalid response from pcsc_list_readers\n");
1528 break;
1530 nreader -= strlen (p)+1;
1531 p += strlen (p) + 1;
1534 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1535 if (!reader_table[slot].rdrname)
1537 log_error ("error allocating memory for reader name\n");
1538 pcsc_release_context (reader_table[slot].pcsc.context);
1539 reader_table[slot].used = 0;
1540 return -1;
1542 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1543 xfree (list);
1544 list = NULL;
1546 reader_table[slot].pcsc.card = 0;
1547 reader_table[slot].atrlen = 0;
1548 reader_table[slot].last_status = 0;
1550 reader_table[slot].connect_card = connect_pcsc_card;
1551 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1552 reader_table[slot].close_reader = close_pcsc_reader;
1553 reader_table[slot].reset_reader = reset_pcsc_reader;
1554 reader_table[slot].get_status_reader = pcsc_get_status;
1555 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1556 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1558 dump_reader_status (slot);
1559 return slot;
1561 #endif /*!NEED_PCSC_WRAPPER */
1564 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1565 needed to cope with different thread models and other peculiarities
1566 of libpcsclite. */
1567 #ifdef NEED_PCSC_WRAPPER
1568 static int
1569 open_pcsc_reader_wrapped (const char *portstr)
1571 int slot;
1572 reader_table_t slotp;
1573 int fd, rp[2], wp[2];
1574 int n, i;
1575 pid_t pid;
1576 size_t len;
1577 unsigned char msgbuf[9];
1578 int err;
1579 unsigned int dummy_status;
1580 int sw = SW_HOST_CARD_IO_ERROR;
1581 /* Note that we use the constant and not the fucntion because this
1582 code won't be be used under Windows. */
1583 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1585 if (access (wrapperpgm, X_OK))
1587 log_error ("can't run PC/SC access module `%s': %s\n",
1588 wrapperpgm, strerror (errno));
1589 return -1;
1592 slot = new_reader_slot ();
1593 if (slot == -1)
1594 return -1;
1595 slotp = reader_table + slot;
1597 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
1598 the common directy but implement it directly so that this file
1599 may still be source copied. */
1601 if (pipe (rp) == -1)
1603 log_error ("error creating a pipe: %s\n", strerror (errno));
1604 slotp->used = 0;
1605 return -1;
1607 if (pipe (wp) == -1)
1609 log_error ("error creating a pipe: %s\n", strerror (errno));
1610 close (rp[0]);
1611 close (rp[1]);
1612 slotp->used = 0;
1613 return -1;
1616 pid = fork ();
1617 if (pid == -1)
1619 log_error ("error forking process: %s\n", strerror (errno));
1620 close (rp[0]);
1621 close (rp[1]);
1622 close (wp[0]);
1623 close (wp[1]);
1624 slotp->used = 0;
1625 return -1;
1627 slotp->pcsc.pid = pid;
1629 if (!pid)
1630 { /*
1631 === Child ===
1634 /* Double fork. */
1635 pid = fork ();
1636 if (pid == -1)
1637 _exit (31);
1638 if (pid)
1639 _exit (0); /* Immediate exit this parent, so that the child
1640 gets cleaned up by the init process. */
1642 /* Connect our pipes. */
1643 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1644 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1645 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1646 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1648 /* Send stderr to the bit bucket. */
1649 fd = open ("/dev/null", O_WRONLY);
1650 if (fd == -1)
1651 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1652 if (fd != 2 && dup2 (fd, 2) == -1)
1653 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1655 /* Close all other files. */
1656 close_all_fds (3, NULL);
1658 execl (wrapperpgm,
1659 "pcsc-wrapper",
1660 "--",
1661 "1", /* API version */
1662 opt.pcsc_driver, /* Name of the PC/SC library. */
1663 NULL);
1664 _exit (31);
1668 === Parent ===
1670 close (wp[0]);
1671 close (rp[1]);
1672 slotp->pcsc.req_fd = wp[1];
1673 slotp->pcsc.rsp_fd = rp[0];
1675 /* Wait for the intermediate child to terminate. */
1676 #ifdef USE_GNU_PTH
1677 #define WAIT pth_waitpid
1678 #else
1679 #define WAIT waitpid
1680 #endif
1681 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1683 #undef WAIT
1685 /* Now send the open request. */
1686 msgbuf[0] = 0x01; /* OPEN command. */
1687 len = portstr? strlen (portstr):0;
1688 msgbuf[1] = (len >> 24);
1689 msgbuf[2] = (len >> 16);
1690 msgbuf[3] = (len >> 8);
1691 msgbuf[4] = (len );
1692 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1693 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1695 log_error ("error sending PC/SC OPEN request: %s\n",
1696 strerror (errno));
1697 goto command_failed;
1699 /* Read the response. */
1700 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1702 log_error ("error receiving PC/SC OPEN response: %s\n",
1703 i? strerror (errno) : "premature EOF");
1704 goto command_failed;
1706 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1707 if (msgbuf[0] != 0x81 || len < 4)
1709 log_error ("invalid response header from PC/SC received\n");
1710 goto command_failed;
1712 len -= 4; /* Already read the error code. */
1713 if (len > DIM (slotp->atr))
1715 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1716 (unsigned long)len);
1717 goto command_failed;
1719 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1720 | (msgbuf[7] << 8 ) | msgbuf[8]);
1721 if (err)
1723 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1724 sw = pcsc_error_to_sw (err);
1725 goto command_failed;
1728 slotp->last_status = 0;
1730 /* The open request may return a zero for the ATR length to
1731 indicate that no card is present. */
1732 n = len;
1733 if (n)
1735 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1737 log_error ("error receiving PC/SC OPEN response: %s\n",
1738 i? strerror (errno) : "premature EOF");
1739 goto command_failed;
1741 /* If we got to here we know that a card is present
1742 and usable. Thus remember this. */
1743 slotp->last_status = ( APDU_CARD_USABLE
1744 | APDU_CARD_PRESENT
1745 | APDU_CARD_ACTIVE);
1747 slotp->atrlen = len;
1749 reader_table[slot].close_reader = close_pcsc_reader;
1750 reader_table[slot].reset_reader = reset_pcsc_reader;
1751 reader_table[slot].get_status_reader = pcsc_get_status;
1752 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1753 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1755 /* Read the status so that IS_T0 will be set. */
1756 pcsc_get_status (slot, &dummy_status);
1758 dump_reader_status (slot);
1759 return slot;
1761 command_failed:
1762 close (slotp->pcsc.req_fd);
1763 close (slotp->pcsc.rsp_fd);
1764 slotp->pcsc.req_fd = -1;
1765 slotp->pcsc.rsp_fd = -1;
1766 kill (slotp->pcsc.pid, SIGTERM);
1767 slotp->pcsc.pid = (pid_t)(-1);
1768 slotp->used = 0;
1769 /* There is no way to return SW. */
1770 return -1;
1773 #endif /*NEED_PCSC_WRAPPER*/
1776 static int
1777 open_pcsc_reader (const char *portstr)
1779 #ifdef NEED_PCSC_WRAPPER
1780 return open_pcsc_reader_wrapped (portstr);
1781 #else
1782 return open_pcsc_reader_direct (portstr);
1783 #endif
1788 #ifdef HAVE_LIBUSB
1790 Internal CCID driver interface.
1794 static void
1795 dump_ccid_reader_status (int slot)
1797 log_info ("reader slot %d: using ccid driver\n", slot);
1800 static int
1801 close_ccid_reader (int slot)
1803 ccid_close_reader (reader_table[slot].ccid.handle);
1804 reader_table[slot].used = 0;
1805 return 0;
1809 static int
1810 shutdown_ccid_reader (int slot)
1812 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1813 return 0;
1817 static int
1818 reset_ccid_reader (int slot)
1820 int err;
1821 reader_table_t slotp = reader_table + slot;
1822 unsigned char atr[33];
1823 size_t atrlen;
1825 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1826 if (err)
1827 return err;
1828 /* If the reset was successful, update the ATR. */
1829 assert (sizeof slotp->atr >= sizeof atr);
1830 slotp->atrlen = atrlen;
1831 memcpy (slotp->atr, atr, atrlen);
1832 dump_reader_status (slot);
1833 return 0;
1837 static int
1838 get_status_ccid (int slot, unsigned int *status)
1840 int rc;
1841 int bits;
1843 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1844 if (rc)
1845 return -1;
1847 if (bits == 0)
1848 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1849 else if (bits == 1)
1850 *status = APDU_CARD_PRESENT;
1851 else
1852 *status = 0;
1854 return 0;
1858 /* Actually send the APDU of length APDULEN to SLOT and return a
1859 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1860 set to BUFLEN. Returns: Internal CCID driver error code. */
1861 static int
1862 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1863 unsigned char *buffer, size_t *buflen,
1864 struct pininfo_s *pininfo)
1866 long err;
1867 size_t maxbuflen;
1869 /* If we don't have an ATR, we need to reset the reader first. */
1870 if (!reader_table[slot].atrlen
1871 && (err = reset_ccid_reader (slot)))
1872 return err;
1874 if (DBG_CARD_IO)
1875 log_printhex (" raw apdu:", apdu, apdulen);
1877 maxbuflen = *buflen;
1878 if (pininfo)
1879 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1880 apdu, apdulen,
1881 pininfo->mode,
1882 pininfo->minlen,
1883 pininfo->maxlen,
1884 pininfo->padlen,
1885 buffer, maxbuflen, buflen);
1886 else
1887 err = ccid_transceive (reader_table[slot].ccid.handle,
1888 apdu, apdulen,
1889 buffer, maxbuflen, buflen);
1890 if (err)
1891 log_error ("ccid_transceive failed: (0x%lx)\n",
1892 err);
1894 return err;
1898 /* Check whether the CCID reader supports the ISO command code COMMAND
1899 on the keypad. Return 0 on success. For a description of the pin
1900 parameters, see ccid-driver.c */
1901 static int
1902 check_ccid_keypad (int slot, int command, int pin_mode,
1903 int pinlen_min, int pinlen_max, int pin_padlen)
1905 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1907 apdu[1] = command;
1908 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1909 apdu, sizeof apdu,
1910 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1911 NULL, 0, NULL);
1915 /* Open the reader and try to read an ATR. */
1916 static int
1917 open_ccid_reader (const char *portstr)
1919 int err;
1920 int slot;
1921 reader_table_t slotp;
1923 slot = new_reader_slot ();
1924 if (slot == -1)
1925 return -1;
1926 slotp = reader_table + slot;
1928 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1929 if (err)
1931 slotp->used = 0;
1932 return -1;
1935 err = ccid_get_atr (slotp->ccid.handle,
1936 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1937 if (err)
1939 slotp->atrlen = 0;
1940 err = 0;
1942 else
1944 /* If we got to here we know that a card is present
1945 and usable. Thus remember this. */
1946 reader_table[slot].last_status = (APDU_CARD_USABLE
1947 | APDU_CARD_PRESENT
1948 | APDU_CARD_ACTIVE);
1951 reader_table[slot].close_reader = close_ccid_reader;
1952 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1953 reader_table[slot].reset_reader = reset_ccid_reader;
1954 reader_table[slot].get_status_reader = get_status_ccid;
1955 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1956 reader_table[slot].check_keypad = check_ccid_keypad;
1957 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1958 /* Our CCID reader code does not support T=0 at all, thus reset the
1959 flag. */
1960 reader_table[slot].is_t0 = 0;
1962 dump_reader_status (slot);
1963 return slot;
1968 #endif /* HAVE_LIBUSB */
1972 #ifdef USE_G10CODE_RAPDU
1974 The Remote APDU Interface.
1976 This uses the Remote APDU protocol to contact a reader.
1978 The port number is actually an index into the list of ports as
1979 returned via the protocol.
1983 static int
1984 rapdu_status_to_sw (int status)
1986 int rc;
1988 switch (status)
1990 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1992 case RAPDU_STATUS_INVCMD:
1993 case RAPDU_STATUS_INVPROT:
1994 case RAPDU_STATUS_INVSEQ:
1995 case RAPDU_STATUS_INVCOOKIE:
1996 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1998 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1999 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2000 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2001 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2002 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2003 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2005 default: rc = SW_HOST_GENERAL_ERROR; break;
2008 return rc;
2013 static int
2014 close_rapdu_reader (int slot)
2016 rapdu_release (reader_table[slot].rapdu.handle);
2017 reader_table[slot].used = 0;
2018 return 0;
2022 static int
2023 reset_rapdu_reader (int slot)
2025 int err;
2026 reader_table_t slotp;
2027 rapdu_msg_t msg = NULL;
2029 slotp = reader_table + slot;
2031 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2032 if (err)
2034 log_error ("sending rapdu command RESET failed: %s\n",
2035 err < 0 ? strerror (errno): rapdu_strerror (err));
2036 rapdu_msg_release (msg);
2037 return rapdu_status_to_sw (err);
2039 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2040 if (err)
2042 log_error ("receiving rapdu message failed: %s\n",
2043 err < 0 ? strerror (errno): rapdu_strerror (err));
2044 rapdu_msg_release (msg);
2045 return rapdu_status_to_sw (err);
2047 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2049 int sw = rapdu_status_to_sw (msg->cmd);
2050 log_error ("rapdu command RESET failed: %s\n",
2051 rapdu_strerror (msg->cmd));
2052 rapdu_msg_release (msg);
2053 return sw;
2055 if (msg->datalen > DIM (slotp->atr))
2057 log_error ("ATR returned by the RAPDU layer is too large\n");
2058 rapdu_msg_release (msg);
2059 return SW_HOST_INV_VALUE;
2061 slotp->atrlen = msg->datalen;
2062 memcpy (slotp->atr, msg->data, msg->datalen);
2064 rapdu_msg_release (msg);
2065 return 0;
2069 static int
2070 my_rapdu_get_status (int slot, unsigned int *status)
2072 int err;
2073 reader_table_t slotp;
2074 rapdu_msg_t msg = NULL;
2075 int oldslot;
2077 slotp = reader_table + slot;
2079 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2080 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2081 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2082 if (err)
2084 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2085 err < 0 ? strerror (errno): rapdu_strerror (err));
2086 return rapdu_status_to_sw (err);
2088 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2089 if (err)
2091 log_error ("receiving rapdu message failed: %s\n",
2092 err < 0 ? strerror (errno): rapdu_strerror (err));
2093 rapdu_msg_release (msg);
2094 return rapdu_status_to_sw (err);
2096 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2098 int sw = rapdu_status_to_sw (msg->cmd);
2099 log_error ("rapdu command GET_STATUS failed: %s\n",
2100 rapdu_strerror (msg->cmd));
2101 rapdu_msg_release (msg);
2102 return sw;
2104 *status = msg->data[0];
2106 rapdu_msg_release (msg);
2107 return 0;
2111 /* Actually send the APDU of length APDULEN to SLOT and return a
2112 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2113 set to BUFLEN. Returns: APDU error code. */
2114 static int
2115 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2116 unsigned char *buffer, size_t *buflen,
2117 struct pininfo_s *pininfo)
2119 int err;
2120 reader_table_t slotp;
2121 rapdu_msg_t msg = NULL;
2122 size_t maxlen = *buflen;
2124 slotp = reader_table + slot;
2126 *buflen = 0;
2127 if (DBG_CARD_IO)
2128 log_printhex (" APDU_data:", apdu, apdulen);
2130 if (apdulen < 4)
2132 log_error ("rapdu_send_apdu: APDU is too short\n");
2133 return SW_HOST_INV_VALUE;
2136 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2137 if (err)
2139 log_error ("sending rapdu command APDU failed: %s\n",
2140 err < 0 ? strerror (errno): rapdu_strerror (err));
2141 rapdu_msg_release (msg);
2142 return rapdu_status_to_sw (err);
2144 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2145 if (err)
2147 log_error ("receiving rapdu message failed: %s\n",
2148 err < 0 ? strerror (errno): rapdu_strerror (err));
2149 rapdu_msg_release (msg);
2150 return rapdu_status_to_sw (err);
2152 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2154 int sw = rapdu_status_to_sw (msg->cmd);
2155 log_error ("rapdu command APDU failed: %s\n",
2156 rapdu_strerror (msg->cmd));
2157 rapdu_msg_release (msg);
2158 return sw;
2161 if (msg->datalen > maxlen)
2163 log_error ("rapdu response apdu too large\n");
2164 rapdu_msg_release (msg);
2165 return SW_HOST_INV_VALUE;
2168 *buflen = msg->datalen;
2169 memcpy (buffer, msg->data, msg->datalen);
2171 rapdu_msg_release (msg);
2172 return 0;
2175 static int
2176 open_rapdu_reader (int portno,
2177 const unsigned char *cookie, size_t length,
2178 int (*readfnc) (void *opaque,
2179 void *buffer, size_t size),
2180 void *readfnc_value,
2181 int (*writefnc) (void *opaque,
2182 const void *buffer, size_t size),
2183 void *writefnc_value,
2184 void (*closefnc) (void *opaque),
2185 void *closefnc_value)
2187 int err;
2188 int slot;
2189 reader_table_t slotp;
2190 rapdu_msg_t msg = NULL;
2192 slot = new_reader_slot ();
2193 if (slot == -1)
2194 return -1;
2195 slotp = reader_table + slot;
2197 slotp->rapdu.handle = rapdu_new ();
2198 if (!slotp->rapdu.handle)
2200 slotp->used = 0;
2201 return -1;
2204 rapdu_set_reader (slotp->rapdu.handle, portno);
2206 rapdu_set_iofunc (slotp->rapdu.handle,
2207 readfnc, readfnc_value,
2208 writefnc, writefnc_value,
2209 closefnc, closefnc_value);
2210 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2212 /* First try to get the current ATR, but if the card is inactive
2213 issue a reset instead. */
2214 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2215 if (err == RAPDU_STATUS_NEEDRESET)
2216 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2217 if (err)
2219 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2220 err < 0 ? strerror (errno): rapdu_strerror (err));
2221 goto failure;
2223 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2224 if (err)
2226 log_info ("receiving rapdu message failed: %s\n",
2227 err < 0 ? strerror (errno): rapdu_strerror (err));
2228 goto failure;
2230 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2232 log_info ("rapdu command GET ATR failed: %s\n",
2233 rapdu_strerror (msg->cmd));
2234 goto failure;
2236 if (msg->datalen > DIM (slotp->atr))
2238 log_error ("ATR returned by the RAPDU layer is too large\n");
2239 goto failure;
2241 slotp->atrlen = msg->datalen;
2242 memcpy (slotp->atr, msg->data, msg->datalen);
2244 reader_table[slot].close_reader = close_rapdu_reader;
2245 reader_table[slot].reset_reader = reset_rapdu_reader;
2246 reader_table[slot].get_status_reader = my_rapdu_get_status;
2247 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2248 reader_table[slot].check_keypad = NULL;
2249 reader_table[slot].dump_status_reader = NULL;
2251 dump_reader_status (slot);
2252 rapdu_msg_release (msg);
2253 return slot;
2255 failure:
2256 rapdu_msg_release (msg);
2257 rapdu_release (slotp->rapdu.handle);
2258 slotp->used = 0;
2259 return -1;
2262 #endif /*USE_G10CODE_RAPDU*/
2267 Driver Access
2271 static int
2272 lock_slot (int slot)
2274 #ifdef USE_GNU_PTH
2275 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2277 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2278 return SW_HOST_LOCKING_FAILED;
2280 #endif /*USE_GNU_PTH*/
2281 return 0;
2284 static int
2285 trylock_slot (int slot)
2287 #ifdef USE_GNU_PTH
2288 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2290 if (errno == EBUSY)
2291 return SW_HOST_BUSY;
2292 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2293 return SW_HOST_LOCKING_FAILED;
2295 #endif /*USE_GNU_PTH*/
2296 return 0;
2299 static void
2300 unlock_slot (int slot)
2302 #ifdef USE_GNU_PTH
2303 if (!pth_mutex_release (&reader_table[slot].lock))
2304 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2305 #endif /*USE_GNU_PTH*/
2309 /* Open the reader and return an internal slot number or -1 on
2310 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2311 the first USB reader. For PC/SC the first listed reader). */
2313 apdu_open_reader (const char *portstr)
2315 static int pcsc_api_loaded, ct_api_loaded;
2317 #ifdef HAVE_LIBUSB
2318 if (!opt.disable_ccid)
2320 int slot, i;
2321 const char *s;
2323 slot = open_ccid_reader (portstr);
2324 if (slot != -1)
2325 return slot; /* got one */
2327 /* If a CCID reader specification has been given, the user does
2328 not want a fallback to other drivers. */
2329 if (portstr)
2330 for (s=portstr, i=0; *s; s++)
2331 if (*s == ':' && (++i == 3))
2332 return -1;
2335 #endif /* HAVE_LIBUSB */
2337 if (opt.ctapi_driver && *opt.ctapi_driver)
2339 int port = portstr? atoi (portstr) : 32768;
2341 if (!ct_api_loaded)
2343 void *handle;
2345 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2346 if (!handle)
2348 log_error ("apdu_open_reader: failed to open driver: %s\n",
2349 dlerror ());
2350 return -1;
2352 CT_init = dlsym (handle, "CT_init");
2353 CT_data = dlsym (handle, "CT_data");
2354 CT_close = dlsym (handle, "CT_close");
2355 if (!CT_init || !CT_data || !CT_close)
2357 log_error ("apdu_open_reader: invalid CT-API driver\n");
2358 dlclose (handle);
2359 return -1;
2361 ct_api_loaded = 1;
2363 return open_ct_reader (port);
2367 /* No ctAPI configured, so lets try the PC/SC API */
2368 if (!pcsc_api_loaded)
2370 #ifndef NEED_PCSC_WRAPPER
2371 void *handle;
2373 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2374 if (!handle)
2376 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2377 opt.pcsc_driver, dlerror ());
2378 return -1;
2381 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2382 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2383 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2384 #if defined(_WIN32) || defined(__CYGWIN__)
2385 if (!pcsc_list_readers)
2386 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2387 #endif
2388 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2389 #if defined(_WIN32) || defined(__CYGWIN__)
2390 if (!pcsc_get_status_change)
2391 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2392 #endif
2393 pcsc_connect = dlsym (handle, "SCardConnect");
2394 #if defined(_WIN32) || defined(__CYGWIN__)
2395 if (!pcsc_connect)
2396 pcsc_connect = dlsym (handle, "SCardConnectA");
2397 #endif
2398 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2399 #if defined(_WIN32) || defined(__CYGWIN__)
2400 if (!pcsc_reconnect)
2401 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2402 #endif
2403 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2404 pcsc_status = dlsym (handle, "SCardStatus");
2405 #if defined(_WIN32) || defined(__CYGWIN__)
2406 if (!pcsc_status)
2407 pcsc_status = dlsym (handle, "SCardStatusA");
2408 #endif
2409 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2410 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2411 pcsc_transmit = dlsym (handle, "SCardTransmit");
2412 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2414 if (!pcsc_establish_context
2415 || !pcsc_release_context
2416 || !pcsc_list_readers
2417 || !pcsc_get_status_change
2418 || !pcsc_connect
2419 || !pcsc_reconnect
2420 || !pcsc_disconnect
2421 || !pcsc_status
2422 || !pcsc_begin_transaction
2423 || !pcsc_end_transaction
2424 || !pcsc_transmit
2425 /* || !pcsc_set_timeout */)
2427 /* Note that set_timeout is currently not used and also not
2428 available under Windows. */
2429 log_error ("apdu_open_reader: invalid PC/SC driver "
2430 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2431 !!pcsc_establish_context,
2432 !!pcsc_release_context,
2433 !!pcsc_list_readers,
2434 !!pcsc_get_status_change,
2435 !!pcsc_connect,
2436 !!pcsc_reconnect,
2437 !!pcsc_disconnect,
2438 !!pcsc_status,
2439 !!pcsc_begin_transaction,
2440 !!pcsc_end_transaction,
2441 !!pcsc_transmit,
2442 !!pcsc_set_timeout );
2443 dlclose (handle);
2444 return -1;
2446 #endif /*!NEED_PCSC_WRAPPER*/
2447 pcsc_api_loaded = 1;
2450 return open_pcsc_reader (portstr);
2454 /* Open an remote reader and return an internal slot number or -1 on
2455 error. This function is an alternative to apdu_open_reader and used
2456 with remote readers only. Note that the supplied CLOSEFNC will
2457 only be called once and the slot will not be valid afther this.
2459 If PORTSTR is NULL we default to the first availabe port.
2462 apdu_open_remote_reader (const char *portstr,
2463 const unsigned char *cookie, size_t length,
2464 int (*readfnc) (void *opaque,
2465 void *buffer, size_t size),
2466 void *readfnc_value,
2467 int (*writefnc) (void *opaque,
2468 const void *buffer, size_t size),
2469 void *writefnc_value,
2470 void (*closefnc) (void *opaque),
2471 void *closefnc_value)
2473 #ifdef USE_G10CODE_RAPDU
2474 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2475 cookie, length,
2476 readfnc, readfnc_value,
2477 writefnc, writefnc_value,
2478 closefnc, closefnc_value);
2479 #else
2480 (void)portstr;
2481 (void)cookie;
2482 (void)length;
2483 (void)readfnc;
2484 (void)readfnc_value;
2485 (void)writefnc;
2486 (void)writefnc_value;
2487 (void)closefnc;
2488 (void)closefnc_value;
2489 #ifdef _WIN32
2490 errno = ENOENT;
2491 #else
2492 errno = ENOSYS;
2493 #endif
2494 return -1;
2495 #endif
2500 apdu_close_reader (int slot)
2502 int sw;
2504 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2505 return SW_HOST_NO_DRIVER;
2506 sw = apdu_disconnect (slot);
2507 if (sw)
2508 return sw;
2509 if (reader_table[slot].close_reader)
2510 return reader_table[slot].close_reader (slot);
2511 return SW_HOST_NOT_SUPPORTED;
2514 /* Shutdown a reader; that is basically the same as a close but keeps
2515 the handle ready for later use. A apdu_reset_reader or apdu_connect
2516 should be used to get it active again. */
2518 apdu_shutdown_reader (int slot)
2520 int sw;
2522 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2523 return SW_HOST_NO_DRIVER;
2524 sw = apdu_disconnect (slot);
2525 if (sw)
2526 return sw;
2527 if (reader_table[slot].shutdown_reader)
2528 return reader_table[slot].shutdown_reader (slot);
2529 return SW_HOST_NOT_SUPPORTED;
2532 /* Enumerate all readers and return information on whether this reader
2533 is in use. The caller should start with SLOT set to 0 and
2534 increment it with each call until an error is returned. */
2536 apdu_enum_reader (int slot, int *used)
2538 if (slot < 0 || slot >= MAX_READER)
2539 return SW_HOST_NO_DRIVER;
2540 *used = reader_table[slot].used;
2541 return 0;
2545 /* Connect a card. This is used to power up the card and make sure
2546 that an ATR is available. */
2548 apdu_connect (int slot)
2550 int sw;
2552 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2553 return SW_HOST_NO_DRIVER;
2555 /* Only if the access method provides a connect function we use it.
2556 If not, we expect that the card has been implicitly connected by
2557 apdu_open_reader. */
2558 if (reader_table[slot].connect_card)
2560 sw = lock_slot (slot);
2561 if (!sw)
2563 sw = reader_table[slot].connect_card (slot);
2564 unlock_slot (slot);
2567 else
2568 sw = 0;
2570 /* We need to call apdu_get_status_internal, so that the last-status
2571 machinery gets setup properly even if a card is inserted while
2572 scdaemon is fired up and apdu_get_status has not yet been called.
2573 Without that we would force a reset of the card with the next
2574 call to apdu_get_status. */
2575 apdu_get_status_internal (slot, 1, 1, NULL, NULL);
2577 return sw;
2582 apdu_disconnect (int slot)
2584 int sw;
2586 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2587 return SW_HOST_NO_DRIVER;
2589 if (reader_table[slot].disconnect_card)
2591 sw = lock_slot (slot);
2592 if (!sw)
2594 sw = reader_table[slot].disconnect_card (slot);
2595 unlock_slot (slot);
2598 else
2599 sw = 0;
2600 return sw;
2605 /* Do a reset for the card in reader at SLOT. */
2607 apdu_reset (int slot)
2609 int sw;
2611 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2612 return SW_HOST_NO_DRIVER;
2614 if ((sw = lock_slot (slot)))
2615 return sw;
2617 reader_table[slot].last_status = 0;
2618 if (reader_table[slot].reset_reader)
2619 sw = reader_table[slot].reset_reader (slot);
2621 if (!sw)
2623 /* If we got to here we know that a card is present
2624 and usable. Thus remember this. */
2625 reader_table[slot].last_status = (APDU_CARD_USABLE
2626 | APDU_CARD_PRESENT
2627 | APDU_CARD_ACTIVE);
2630 unlock_slot (slot);
2631 return sw;
2635 /* Activate a card if it has not yet been done. This is a kind of
2636 reset-if-required. It is useful to test for presence of a card
2637 before issuing a bunch of apdu commands. It does not wait on a
2638 locked card. */
2640 apdu_activate (int slot)
2642 int sw;
2643 unsigned int s;
2645 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2646 return SW_HOST_NO_DRIVER;
2648 if ((sw = trylock_slot (slot)))
2649 return sw;
2651 if (reader_table[slot].get_status_reader)
2652 sw = reader_table[slot].get_status_reader (slot, &s);
2654 if (!sw)
2656 if (!(s & 2)) /* Card not present. */
2657 sw = SW_HOST_NO_CARD;
2658 else if ( ((s & 2) && !(s & 4))
2659 || !reader_table[slot].atrlen )
2661 /* We don't have an ATR or a card is present though inactive:
2662 do a reset now. */
2663 if (reader_table[slot].reset_reader)
2665 reader_table[slot].last_status = 0;
2666 sw = reader_table[slot].reset_reader (slot);
2667 if (!sw)
2669 /* If we got to here we know that a card is present
2670 and usable. Thus remember this. */
2671 reader_table[slot].last_status = (APDU_CARD_USABLE
2672 | APDU_CARD_PRESENT
2673 | APDU_CARD_ACTIVE);
2679 unlock_slot (slot);
2680 return sw;
2685 unsigned char *
2686 apdu_get_atr (int slot, size_t *atrlen)
2688 unsigned char *buf;
2690 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2691 return NULL;
2692 if (!reader_table[slot].atrlen)
2693 return NULL;
2694 buf = xtrymalloc (reader_table[slot].atrlen);
2695 if (!buf)
2696 return NULL;
2697 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2698 *atrlen = reader_table[slot].atrlen;
2699 return buf;
2704 /* Retrieve the status for SLOT. The function does only wait for the
2705 card to become available if HANG is set to true. On success the
2706 bits in STATUS will be set to
2708 APDU_CARD_USABLE (bit 0) = card present and usable
2709 APDU_CARD_PRESENT (bit 1) = card present
2710 APDU_CARD_ACTIVE (bit 2) = card active
2711 (bit 3) = card access locked [not yet implemented]
2713 For must applications, testing bit 0 is sufficient.
2715 CHANGED will receive the value of the counter tracking the number
2716 of card insertions. This value may be used to detect a card
2717 change.
2719 static int
2720 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
2721 unsigned int *status, unsigned int *changed)
2723 int sw;
2724 unsigned int s;
2726 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2727 return SW_HOST_NO_DRIVER;
2729 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2730 return sw;
2732 if (reader_table[slot].get_status_reader)
2733 sw = reader_table[slot].get_status_reader (slot, &s);
2735 unlock_slot (slot);
2737 if (sw)
2739 reader_table[slot].last_status = 0;
2740 return sw;
2743 /* Keep track of changes. */
2744 if (s != reader_table[slot].last_status
2745 || !reader_table[slot].any_status )
2747 reader_table[slot].change_counter++;
2748 /* Make sure that the ATR is invalid so that a reset will be
2749 triggered by apdu_activate. */
2750 if (!no_atr_reset)
2751 reader_table[slot].atrlen = 0;
2753 reader_table[slot].any_status = 1;
2754 reader_table[slot].last_status = s;
2756 if (status)
2757 *status = s;
2758 if (changed)
2759 *changed = reader_table[slot].change_counter;
2760 return 0;
2764 /* See above for a description. */
2766 apdu_get_status (int slot, int hang,
2767 unsigned int *status, unsigned int *changed)
2769 return apdu_get_status_internal (slot, hang, 0, status, changed);
2773 /* Check whether the reader supports the ISO command code COMMAND on
2774 the keypad. Return 0 on success. For a description of the pin
2775 parameters, see ccid-driver.c */
2777 apdu_check_keypad (int slot, int command, int pin_mode,
2778 int pinlen_min, int pinlen_max, int pin_padlen)
2780 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2781 return SW_HOST_NO_DRIVER;
2783 if (reader_table[slot].check_keypad)
2784 return reader_table[slot].check_keypad (slot, command,
2785 pin_mode, pinlen_min, pinlen_max,
2786 pin_padlen);
2787 else
2788 return SW_HOST_NOT_SUPPORTED;
2792 /* Dispatcher for the actual send_apdu function. Note, that this
2793 function should be called in locked state. */
2794 static int
2795 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2796 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2798 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2799 return SW_HOST_NO_DRIVER;
2801 if (reader_table[slot].send_apdu_reader)
2802 return reader_table[slot].send_apdu_reader (slot,
2803 apdu, apdulen,
2804 buffer, buflen,
2805 pininfo);
2806 else
2807 return SW_HOST_NOT_SUPPORTED;
2811 /* Core APDU tranceiver function. Parameters are described at
2812 apdu_send_le with the exception of PININFO which indicates keypad
2813 related operations if not NULL. If EXTENDED_MODE is not 0
2814 command chaining or extended length will be used according to these
2815 values:
2816 n < 0 := Use command chaining with the data part limited to -n
2817 in each chunk. If -1 is used a default value is used.
2818 n == 0 := No extended mode or command chaining.
2819 n == 1 := Use extended length for input and output without a
2820 length limit.
2821 n > 1 := Use extended length with up to N bytes.
2824 static int
2825 send_le (int slot, int class, int ins, int p0, int p1,
2826 int lc, const char *data, int le,
2827 unsigned char **retbuf, size_t *retbuflen,
2828 struct pininfo_s *pininfo, int extended_mode)
2830 #define SHORT_RESULT_BUFFER_SIZE 258
2831 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
2832 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2833 unsigned char *result_buffer = NULL;
2834 size_t result_buffer_size;
2835 unsigned char *result;
2836 size_t resultlen;
2837 unsigned char short_apdu_buffer[5+256+1];
2838 unsigned char *apdu_buffer = NULL;
2839 size_t apdu_buffer_size;
2840 unsigned char *apdu;
2841 size_t apdulen;
2842 int sw;
2843 long rc; /* We need a long here due to PC/SC. */
2844 int did_exact_length_hack = 0;
2845 int use_chaining = 0;
2846 int use_extended_length = 0;
2847 int lc_chunk;
2849 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2850 return SW_HOST_NO_DRIVER;
2852 if (DBG_CARD_IO)
2853 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2854 class, ins, p0, p1, lc, le, extended_mode);
2856 if (lc != -1 && (lc > 255 || lc < 0))
2858 /* Data does not fit into an APDU. What we do now depends on
2859 the EXTENDED_MODE parameter. */
2860 if (!extended_mode)
2861 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2862 else if (extended_mode > 0)
2863 use_extended_length = 1;
2864 else if (extended_mode < 0)
2866 /* Send APDU using chaining mode. */
2867 if (lc > 16384)
2868 return SW_WRONG_LENGTH; /* Sanity check. */
2869 if ((class&0xf0) != 0)
2870 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2871 use_chaining = extended_mode == -1? 255 : -extended_mode;
2872 use_chaining &= 0xff;
2874 else
2875 return SW_HOST_INV_VALUE;
2877 else if (lc == -1 && extended_mode > 0)
2878 use_extended_length = 1;
2880 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2882 /* Expected Data does not fit into an APDU. What we do now
2883 depends on the EXTENDED_MODE parameter. Note that a check
2884 for command chaining does not make sense because we are
2885 looking at Le. */
2886 if (!extended_mode)
2887 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2888 else if (use_extended_length)
2889 ; /* We are already using extended length. */
2890 else if (extended_mode > 0)
2891 use_extended_length = 1;
2892 else
2893 return SW_HOST_INV_VALUE;
2896 if ((!data && lc != -1) || (data && lc == -1))
2897 return SW_HOST_INV_VALUE;
2899 if (use_extended_length)
2901 if (reader_table[slot].is_t0)
2902 return SW_HOST_NOT_SUPPORTED;
2904 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2905 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2906 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2907 if (!apdu_buffer)
2908 return SW_HOST_OUT_OF_CORE;
2909 apdu = apdu_buffer;
2911 else
2913 apdu_buffer_size = sizeof short_apdu_buffer;
2914 apdu = short_apdu_buffer;
2917 if (use_extended_length && (le > 256 || le < 0))
2919 result_buffer_size = le < 0? 4096 : le;
2920 result_buffer = xtrymalloc (result_buffer_size + 10);
2921 if (!result_buffer)
2923 xfree (apdu_buffer);
2924 return SW_HOST_OUT_OF_CORE;
2926 result = result_buffer;
2928 else
2930 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2931 result = short_result_buffer;
2933 #undef SHORT_RESULT_BUFFER_SIZE
2935 if ((sw = lock_slot (slot)))
2937 xfree (apdu_buffer);
2938 xfree (result_buffer);
2939 return sw;
2944 if (use_extended_length)
2946 use_chaining = 0;
2947 apdulen = 0;
2948 apdu[apdulen++] = class;
2949 apdu[apdulen++] = ins;
2950 apdu[apdulen++] = p0;
2951 apdu[apdulen++] = p1;
2952 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
2953 if (lc >= 0)
2955 apdu[apdulen++] = ((lc >> 8) & 0xff);
2956 apdu[apdulen++] = (lc & 0xff);
2957 memcpy (apdu+apdulen, data, lc);
2958 data += lc;
2959 apdulen += lc;
2961 if (le != -1)
2963 apdu[apdulen++] = ((le >> 8) & 0xff);
2964 apdu[apdulen++] = (le & 0xff);
2967 else
2969 apdulen = 0;
2970 apdu[apdulen] = class;
2971 if (use_chaining && lc > 255)
2973 apdu[apdulen] |= 0x10;
2974 assert (use_chaining < 256);
2975 lc_chunk = use_chaining;
2976 lc -= use_chaining;
2978 else
2980 use_chaining = 0;
2981 lc_chunk = lc;
2983 apdulen++;
2984 apdu[apdulen++] = ins;
2985 apdu[apdulen++] = p0;
2986 apdu[apdulen++] = p1;
2987 if (lc_chunk != -1)
2989 apdu[apdulen++] = lc_chunk;
2990 memcpy (apdu+apdulen, data, lc_chunk);
2991 data += lc_chunk;
2992 apdulen += lc_chunk;
2993 /* T=0 does not allow the use of Lc together with Le;
2994 thus disable Le in this case. */
2995 if (reader_table[slot].is_t0)
2996 le = -1;
2998 if (le != -1 && !use_chaining)
2999 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3002 exact_length_hack:
3003 /* As a safeguard don't pass any garbage to the driver. */
3004 assert (apdulen <= apdu_buffer_size);
3005 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3006 resultlen = result_buffer_size;
3007 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3008 if (rc || resultlen < 2)
3010 log_info ("apdu_send_simple(%d) failed: %s\n",
3011 slot, apdu_strerror (rc));
3012 unlock_slot (slot);
3013 xfree (apdu_buffer);
3014 xfree (result_buffer);
3015 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3017 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3018 if (!use_extended_length
3019 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3021 apdu[apdulen-1] = (sw & 0x00ff);
3022 did_exact_length_hack = 1;
3023 goto exact_length_hack;
3026 while (use_chaining && sw == SW_SUCCESS);
3028 if (apdu_buffer)
3030 xfree (apdu_buffer);
3031 apdu_buffer = NULL;
3032 apdu_buffer_size = 0;
3035 /* Store away the returned data but strip the statusword. */
3036 resultlen -= 2;
3037 if (DBG_CARD_IO)
3039 log_debug (" response: sw=%04X datalen=%d\n",
3040 sw, (unsigned int)resultlen);
3041 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3042 log_printhex (" dump: ", result, resultlen);
3045 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3047 if (retbuf)
3049 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3050 if (!*retbuf)
3052 unlock_slot (slot);
3053 xfree (result_buffer);
3054 return SW_HOST_OUT_OF_CORE;
3056 *retbuflen = resultlen;
3057 memcpy (*retbuf, result, resultlen);
3060 else if ((sw & 0xff00) == SW_MORE_DATA)
3062 unsigned char *p = NULL, *tmp;
3063 size_t bufsize = 4096;
3065 /* It is likely that we need to return much more data, so we
3066 start off with a large buffer. */
3067 if (retbuf)
3069 *retbuf = p = xtrymalloc (bufsize);
3070 if (!*retbuf)
3072 unlock_slot (slot);
3073 xfree (result_buffer);
3074 return SW_HOST_OUT_OF_CORE;
3076 assert (resultlen < bufsize);
3077 memcpy (p, result, resultlen);
3078 p += resultlen;
3083 int len = (sw & 0x00ff);
3085 if (DBG_CARD_IO)
3086 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3087 slot, len);
3088 apdu_buffer_size = sizeof short_apdu_buffer;
3089 apdu = short_apdu_buffer;
3090 apdulen = 0;
3091 apdu[apdulen++] = class;
3092 apdu[apdulen++] = 0xC0;
3093 apdu[apdulen++] = 0;
3094 apdu[apdulen++] = 0;
3095 apdu[apdulen++] = len;
3096 assert (apdulen <= apdu_buffer_size);
3097 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3098 resultlen = result_buffer_size;
3099 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3100 if (rc || resultlen < 2)
3102 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3103 slot, apdu_strerror (rc));
3104 unlock_slot (slot);
3105 xfree (result_buffer);
3106 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3108 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3109 resultlen -= 2;
3110 if (DBG_CARD_IO)
3112 log_debug (" more: sw=%04X datalen=%d\n",
3113 sw, (unsigned int)resultlen);
3114 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3115 log_printhex (" dump: ", result, resultlen);
3118 if ((sw & 0xff00) == SW_MORE_DATA
3119 || sw == SW_SUCCESS
3120 || sw == SW_EOF_REACHED )
3122 if (retbuf && resultlen)
3124 if (p - *retbuf + resultlen > bufsize)
3126 bufsize += resultlen > 4096? resultlen: 4096;
3127 tmp = xtryrealloc (*retbuf, bufsize);
3128 if (!tmp)
3130 unlock_slot (slot);
3131 xfree (result_buffer);
3132 return SW_HOST_OUT_OF_CORE;
3134 p = tmp + (p - *retbuf);
3135 *retbuf = tmp;
3137 memcpy (p, result, resultlen);
3138 p += resultlen;
3141 else
3142 log_info ("apdu_send_simple(%d) "
3143 "got unexpected status %04X from get response\n",
3144 slot, sw);
3146 while ((sw & 0xff00) == SW_MORE_DATA);
3148 if (retbuf)
3150 *retbuflen = p - *retbuf;
3151 tmp = xtryrealloc (*retbuf, *retbuflen);
3152 if (tmp)
3153 *retbuf = tmp;
3157 unlock_slot (slot);
3158 xfree (result_buffer);
3160 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3161 log_printhex (" dump: ", *retbuf, *retbuflen);
3163 return sw;
3166 /* Send an APDU to the card in SLOT. The APDU is created from all
3167 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
3168 for LC won't sent this field and the data field; in this case DATA
3169 must also be passed as NULL. If EXTENDED_MODE is not 0 command
3170 chaining or extended length will be used; see send_le for details.
3171 The return value is the status word or -1 for an invalid SLOT or
3172 other non card related error. If RETBUF is not NULL, it will
3173 receive an allocated buffer with the returned data. The length of
3174 that data will be put into *RETBUFLEN. The caller is reponsible
3175 for releasing the buffer even in case of errors. */
3177 apdu_send_le(int slot, int extended_mode,
3178 int class, int ins, int p0, int p1,
3179 int lc, const char *data, int le,
3180 unsigned char **retbuf, size_t *retbuflen)
3182 return send_le (slot, class, ins, p0, p1,
3183 lc, data, le,
3184 retbuf, retbuflen,
3185 NULL, extended_mode);
3189 /* Send an APDU to the card in SLOT. The APDU is created from all
3190 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3191 LC won't sent this field and the data field; in this case DATA must
3192 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3193 or extended length will be used; see send_le for details. The
3194 return value is the status word or -1 for an invalid SLOT or other
3195 non card related error. If RETBUF is not NULL, it will receive an
3196 allocated buffer with the returned data. The length of that data
3197 will be put into *RETBUFLEN. The caller is reponsible for
3198 releasing the buffer even in case of errors. */
3200 apdu_send (int slot, int extended_mode,
3201 int class, int ins, int p0, int p1,
3202 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
3204 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3205 retbuf, retbuflen, NULL, extended_mode);
3208 /* Send an APDU to the card in SLOT. The APDU is created from all
3209 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3210 LC won't sent this field and the data field; in this case DATA must
3211 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3212 or extended length will be used; see send_le for details. The
3213 return value is the status word or -1 for an invalid SLOT or other
3214 non card related error. No data will be returned. */
3216 apdu_send_simple (int slot, int extended_mode,
3217 int class, int ins, int p0, int p1,
3218 int lc, const char *data)
3220 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3221 extended_mode);
3225 /* Same as apdu_send_simple but uses the keypad of the reader. */
3227 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
3228 int lc, const char *data,
3229 int pin_mode,
3230 int pinlen_min, int pinlen_max, int pin_padlen)
3232 struct pininfo_s pininfo;
3234 pininfo.mode = pin_mode;
3235 pininfo.minlen = pinlen_min;
3236 pininfo.maxlen = pinlen_max;
3237 pininfo.padlen = pin_padlen;
3238 return send_le (slot, class, ins, p0, p1, lc, data, -1,
3239 NULL, NULL, &pininfo, 0);
3243 /* This is a more generic version of the apdu sending routine. It
3244 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3245 and returns with an APDU including the status word. With
3246 HANDLE_MORE set to true this function will handle the MORE DATA
3247 status and return all APDUs concatenated with one status word at
3248 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
3249 with a max. result data length of EXTENDED_LENGTH bytes. The
3250 function does not return a regular status word but 0 on success.
3251 If the slot is locked, the function returns immediately with an
3252 error. */
3254 apdu_send_direct (int slot, size_t extended_length,
3255 const unsigned char *apdudata, size_t apdudatalen,
3256 int handle_more,
3257 unsigned char **retbuf, size_t *retbuflen)
3259 #define SHORT_RESULT_BUFFER_SIZE 258
3260 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3261 unsigned char *result_buffer = NULL;
3262 size_t result_buffer_size;
3263 unsigned char *result;
3264 size_t resultlen;
3265 unsigned char short_apdu_buffer[5+256+10];
3266 unsigned char *apdu_buffer = NULL;
3267 unsigned char *apdu;
3268 size_t apdulen;
3269 int sw;
3270 long rc; /* we need a long here due to PC/SC. */
3271 int class;
3273 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3274 return SW_HOST_NO_DRIVER;
3276 if (apdudatalen > 65535)
3277 return SW_HOST_INV_VALUE;
3279 if (apdudatalen > sizeof short_apdu_buffer - 5)
3281 apdu_buffer = xtrymalloc (apdudatalen + 5);
3282 if (!apdu_buffer)
3283 return SW_HOST_OUT_OF_CORE;
3284 apdu = apdu_buffer;
3286 else
3288 apdu = short_apdu_buffer;
3290 apdulen = apdudatalen;
3291 memcpy (apdu, apdudata, apdudatalen);
3292 class = apdulen? *apdu : 0;
3294 if (extended_length >= 256 && extended_length <= 65536)
3296 result_buffer_size = extended_length;
3297 result_buffer = xtrymalloc (result_buffer_size + 10);
3298 if (!result_buffer)
3300 xfree (apdu_buffer);
3301 return SW_HOST_OUT_OF_CORE;
3303 result = result_buffer;
3305 else
3307 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3308 result = short_result_buffer;
3310 #undef SHORT_RESULT_BUFFER_SIZE
3312 if ((sw = trylock_slot (slot)))
3314 xfree (apdu_buffer);
3315 xfree (result_buffer);
3316 return sw;
3319 resultlen = result_buffer_size;
3320 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3321 xfree (apdu_buffer);
3322 apdu_buffer = NULL;
3323 if (rc || resultlen < 2)
3325 log_error ("apdu_send_direct(%d) failed: %s\n",
3326 slot, apdu_strerror (rc));
3327 unlock_slot (slot);
3328 xfree (result_buffer);
3329 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3331 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3332 /* Store away the returned data but strip the statusword. */
3333 resultlen -= 2;
3334 if (DBG_CARD_IO)
3336 log_debug (" response: sw=%04X datalen=%d\n",
3337 sw, (unsigned int)resultlen);
3338 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3339 log_printhex (" dump: ", result, resultlen);
3342 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3344 unsigned char *p = NULL, *tmp;
3345 size_t bufsize = 4096;
3347 /* It is likely that we need to return much more data, so we
3348 start off with a large buffer. */
3349 if (retbuf)
3351 *retbuf = p = xtrymalloc (bufsize + 2);
3352 if (!*retbuf)
3354 unlock_slot (slot);
3355 xfree (result_buffer);
3356 return SW_HOST_OUT_OF_CORE;
3358 assert (resultlen < bufsize);
3359 memcpy (p, result, resultlen);
3360 p += resultlen;
3365 int len = (sw & 0x00ff);
3367 if (DBG_CARD_IO)
3368 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3369 slot, len);
3370 apdu = short_apdu_buffer;
3371 apdulen = 0;
3372 apdu[apdulen++] = class;
3373 apdu[apdulen++] = 0xC0;
3374 apdu[apdulen++] = 0;
3375 apdu[apdulen++] = 0;
3376 apdu[apdulen++] = len;
3377 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3378 resultlen = result_buffer_size;
3379 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3380 if (rc || resultlen < 2)
3382 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3383 slot, apdu_strerror (rc));
3384 unlock_slot (slot);
3385 xfree (result_buffer);
3386 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3388 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3389 resultlen -= 2;
3390 if (DBG_CARD_IO)
3392 log_debug (" more: sw=%04X datalen=%d\n",
3393 sw, (unsigned int)resultlen);
3394 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3395 log_printhex (" dump: ", result, resultlen);
3398 if ((sw & 0xff00) == SW_MORE_DATA
3399 || sw == SW_SUCCESS
3400 || sw == SW_EOF_REACHED )
3402 if (retbuf && resultlen)
3404 if (p - *retbuf + resultlen > bufsize)
3406 bufsize += resultlen > 4096? resultlen: 4096;
3407 tmp = xtryrealloc (*retbuf, bufsize + 2);
3408 if (!tmp)
3410 unlock_slot (slot);
3411 xfree (result_buffer);
3412 return SW_HOST_OUT_OF_CORE;
3414 p = tmp + (p - *retbuf);
3415 *retbuf = tmp;
3417 memcpy (p, result, resultlen);
3418 p += resultlen;
3421 else
3422 log_info ("apdu_send_direct(%d) "
3423 "got unexpected status %04X from get response\n",
3424 slot, sw);
3426 while ((sw & 0xff00) == SW_MORE_DATA);
3428 if (retbuf)
3430 *retbuflen = p - *retbuf;
3431 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3432 if (tmp)
3433 *retbuf = tmp;
3436 else
3438 if (retbuf)
3440 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3441 if (!*retbuf)
3443 unlock_slot (slot);
3444 xfree (result_buffer);
3445 return SW_HOST_OUT_OF_CORE;
3447 *retbuflen = resultlen;
3448 memcpy (*retbuf, result, resultlen);
3452 unlock_slot (slot);
3453 xfree (result_buffer);
3455 /* Append the status word. Note that we reserved the two extra
3456 bytes while allocating the buffer. */
3457 if (retbuf)
3459 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3460 (*retbuf)[(*retbuflen)++] = sw;
3463 if (DBG_CARD_IO && retbuf)
3464 log_printhex (" dump: ", *retbuf, *retbuflen);
3466 return 0;