Start a new development branch.
[gnupg.git] / scd / apdu.c
blobf382aea85675d2ab0f11f192b9688db22de9aea2
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/>.
20 /* NOTE: This module is also used by other software, thus the use of
21 the macro USE_GNU_PTH is mandatory. For GnuPG this macro is
22 guaranteed to be defined true. */
24 #include <config.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <signal.h>
31 #ifdef USE_GNU_PTH
32 # include <unistd.h>
33 # include <fcntl.h>
34 # include <pth.h>
35 #endif
38 /* If requested include the definitions for the remote APDU protocol
39 code. */
40 #ifdef USE_G10CODE_RAPDU
41 #include "rapdu.h"
42 #endif /*USE_G10CODE_RAPDU*/
44 #if defined(GNUPG_SCD_MAIN_HEADER)
45 #include GNUPG_SCD_MAIN_HEADER
46 #elif GNUPG_MAJOR_VERSION == 1
47 /* This is used with GnuPG version < 1.9. The code has been source
48 copied from the current GnuPG >= 1.9 and is maintained over
49 there. */
50 #include "options.h"
51 #include "errors.h"
52 #include "memory.h"
53 #include "util.h"
54 #include "i18n.h"
55 #include "dynload.h"
56 #include "cardglue.h"
57 #else /* GNUPG_MAJOR_VERSION != 1 */
58 #include "scdaemon.h"
59 #include "exechelp.h"
60 #endif /* GNUPG_MAJOR_VERSION != 1 */
62 #include "apdu.h"
63 #include "ccid-driver.h"
66 /* Due to conflicting use of threading libraries we usually can't link
67 against libpcsclite. Instead we use a wrapper program. */
68 #ifdef USE_GNU_PTH
69 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
70 #define NEED_PCSC_WRAPPER 1
71 #endif
72 #endif
75 #define MAX_READER 4 /* Number of readers we support concurrently. */
78 #if defined(_WIN32) || defined(__CYGWIN__)
79 #define DLSTDCALL __stdcall
80 #else
81 #define DLSTDCALL
82 #endif
85 /* Helper to pass parameters related to keypad based operations. */
86 struct pininfo_s
88 int mode;
89 int minlen;
90 int maxlen;
91 int padlen;
94 /* A structure to collect information pertaining to one reader
95 slot. */
96 struct reader_table_s {
97 int used; /* True if slot is used. */
98 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
100 /* Function pointers intialized to the various backends. */
101 int (*connect_card)(int);
102 int (*disconnect_card)(int);
103 int (*close_reader)(int);
104 int (*shutdown_reader)(int);
105 int (*reset_reader)(int);
106 int (*get_status_reader)(int, unsigned int *);
107 int (*send_apdu_reader)(int,unsigned char *,size_t,
108 unsigned char *, size_t *, struct pininfo_s *);
109 int (*check_keypad)(int, int, int, int, int, int);
110 void (*dump_status_reader)(int);
111 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
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;
342 reader_table[reader].set_progress_cb = NULL;
344 reader_table[reader].used = 1;
345 reader_table[reader].any_status = 0;
346 reader_table[reader].last_status = 0;
347 reader_table[reader].is_t0 = 1;
348 #ifdef NEED_PCSC_WRAPPER
349 reader_table[reader].pcsc.req_fd = -1;
350 reader_table[reader].pcsc.rsp_fd = -1;
351 reader_table[reader].pcsc.pid = (pid_t)(-1);
352 #endif
354 return reader;
358 static void
359 dump_reader_status (int slot)
361 if (!opt.verbose)
362 return;
364 if (reader_table[slot].dump_status_reader)
365 reader_table[slot].dump_status_reader (slot);
367 if (reader_table[slot].status != -1
368 && reader_table[slot].atrlen)
370 log_info ("slot %d: ATR=", slot);
371 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
377 static const char *
378 host_sw_string (long err)
380 switch (err)
382 case 0: return "okay";
383 case SW_HOST_OUT_OF_CORE: return "out of core";
384 case SW_HOST_INV_VALUE: return "invalid value";
385 case SW_HOST_NO_DRIVER: return "no driver";
386 case SW_HOST_NOT_SUPPORTED: return "not supported";
387 case SW_HOST_LOCKING_FAILED: return "locking failed";
388 case SW_HOST_BUSY: return "busy";
389 case SW_HOST_NO_CARD: return "no card";
390 case SW_HOST_CARD_INACTIVE: return "card inactive";
391 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
392 case SW_HOST_GENERAL_ERROR: return "general error";
393 case SW_HOST_NO_READER: return "no reader";
394 case SW_HOST_ABORTED: return "aborted";
395 case SW_HOST_NO_KEYPAD: return "no keypad";
396 case SW_HOST_ALREADY_CONNECTED: return "already connected";
397 default: return "unknown host status error";
402 const char *
403 apdu_strerror (int rc)
405 switch (rc)
407 case SW_EOF_REACHED : return "eof reached";
408 case SW_EEPROM_FAILURE : return "eeprom failure";
409 case SW_WRONG_LENGTH : return "wrong length";
410 case SW_CHV_WRONG : return "CHV wrong";
411 case SW_CHV_BLOCKED : return "CHV blocked";
412 case SW_USE_CONDITIONS : return "use conditions not satisfied";
413 case SW_BAD_PARAMETER : return "bad parameter";
414 case SW_NOT_SUPPORTED : return "not supported";
415 case SW_FILE_NOT_FOUND : return "file not found";
416 case SW_RECORD_NOT_FOUND:return "record not found";
417 case SW_REF_NOT_FOUND : return "reference not found";
418 case SW_BAD_LC : return "bad Lc";
419 case SW_BAD_P0_P1 : return "bad P0 or P1";
420 case SW_INS_NOT_SUP : return "instruction not supported";
421 case SW_CLA_NOT_SUP : return "class not supported";
422 case SW_SUCCESS : return "success";
423 default:
424 if ((rc & ~0x00ff) == SW_MORE_DATA)
425 return "more data available";
426 if ( (rc & 0x10000) )
427 return host_sw_string (rc);
428 return "unknown status error";
435 ct API Interface
438 static const char *
439 ct_error_string (long err)
441 switch (err)
443 case 0: return "okay";
444 case -1: return "invalid data";
445 case -8: return "ct error";
446 case -10: return "transmission error";
447 case -11: return "memory allocation error";
448 case -128: return "HTSI error";
449 default: return "unknown CT-API error";
454 static void
455 ct_dump_reader_status (int slot)
457 log_info ("reader slot %d: %s\n", slot,
458 reader_table[slot].status == 1? "Processor ICC present" :
459 reader_table[slot].status == 0? "Memory ICC present" :
460 "ICC not present" );
464 /* Wait for the card in SLOT and activate it. Return a status word
465 error or 0 on success. */
466 static int
467 ct_activate_card (int slot)
469 int rc;
470 unsigned char dad[1], sad[1], cmd[11], buf[256];
471 unsigned short buflen;
473 /* Check whether card has been inserted. */
474 dad[0] = 1; /* Destination address: CT. */
475 sad[0] = 2; /* Source address: Host. */
477 cmd[0] = 0x20; /* Class byte. */
478 cmd[1] = 0x13; /* Request status. */
479 cmd[2] = 0x00; /* From kernel. */
480 cmd[3] = 0x80; /* Return card's DO. */
481 cmd[4] = 0x00;
483 buflen = DIM(buf);
485 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
486 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
488 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
489 slot, ct_error_string (rc));
490 return SW_HOST_CARD_IO_ERROR;
493 /* Connected, now activate the card. */
494 dad[0] = 1; /* Destination address: CT. */
495 sad[0] = 2; /* Source address: Host. */
497 cmd[0] = 0x20; /* Class byte. */
498 cmd[1] = 0x12; /* Request ICC. */
499 cmd[2] = 0x01; /* From first interface. */
500 cmd[3] = 0x01; /* Return card's ATR. */
501 cmd[4] = 0x00;
503 buflen = DIM(buf);
505 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
506 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
508 log_error ("ct_activate_card(%d): activation failed: %s\n",
509 slot, ct_error_string (rc));
510 if (!rc)
511 log_printhex (" received data:", buf, buflen);
512 return SW_HOST_CARD_IO_ERROR;
515 /* Store the type and the ATR. */
516 if (buflen - 2 > DIM (reader_table[0].atr))
518 log_error ("ct_activate_card(%d): ATR too long\n", slot);
519 return SW_HOST_CARD_IO_ERROR;
522 reader_table[slot].status = buf[buflen - 1];
523 memcpy (reader_table[slot].atr, buf, buflen - 2);
524 reader_table[slot].atrlen = buflen - 2;
525 return 0;
529 static int
530 close_ct_reader (int slot)
532 CT_close (slot);
533 reader_table[slot].used = 0;
534 return 0;
537 static int
538 reset_ct_reader (int slot)
540 /* FIXME: Check is this is sufficient do do a reset. */
541 return ct_activate_card (slot);
545 static int
546 ct_get_status (int slot, unsigned int *status)
548 (void)slot;
549 /* The status we returned is wrong but we don't care becuase ctAPI
550 is not anymore required. */
551 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
552 return 0;
555 /* Actually send the APDU of length APDULEN to SLOT and return a
556 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
557 set to BUFLEN. Returns: CT API error code. */
558 static int
559 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
560 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
562 int rc;
563 unsigned char dad[1], sad[1];
564 unsigned short ctbuflen;
566 (void)pininfo;
568 /* If we don't have an ATR, we need to reset the reader first. */
569 if (!reader_table[slot].atrlen
570 && (rc = reset_ct_reader (slot)))
571 return rc;
573 dad[0] = 0; /* Destination address: Card. */
574 sad[0] = 2; /* Source address: Host. */
575 ctbuflen = *buflen;
576 if (DBG_CARD_IO)
577 log_printhex (" CT_data:", apdu, apdulen);
578 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
579 *buflen = ctbuflen;
581 return rc? SW_HOST_CARD_IO_ERROR: 0;
586 /* Open a reader and return an internal handle for it. PORT is a
587 non-negative value with the port number of the reader. USB readers
588 do have port numbers starting at 32769. */
589 static int
590 open_ct_reader (int port)
592 int rc, reader;
594 if (port < 0 || port > 0xffff)
596 log_error ("open_ct_reader: invalid port %d requested\n", port);
597 return -1;
599 reader = new_reader_slot ();
600 if (reader == -1)
601 return reader;
602 reader_table[reader].port = port;
604 rc = CT_init (reader, (unsigned short)port);
605 if (rc)
607 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
608 port, ct_error_string (rc));
609 reader_table[reader].used = 0;
610 return -1;
613 /* Only try to activate the card. */
614 rc = ct_activate_card (reader);
615 if (rc)
617 reader_table[reader].atrlen = 0;
618 rc = 0;
621 reader_table[reader].close_reader = close_ct_reader;
622 reader_table[reader].reset_reader = reset_ct_reader;
623 reader_table[reader].get_status_reader = ct_get_status;
624 reader_table[reader].send_apdu_reader = ct_send_apdu;
625 reader_table[reader].check_keypad = NULL;
626 reader_table[reader].dump_status_reader = ct_dump_reader_status;
628 dump_reader_status (reader);
629 return reader;
634 PC/SC Interface
637 #ifdef NEED_PCSC_WRAPPER
638 static int
639 writen (int fd, const void *buf, size_t nbytes)
641 size_t nleft = nbytes;
642 int nwritten;
644 /* log_printhex (" writen:", buf, nbytes); */
646 while (nleft > 0)
648 #ifdef USE_GNU_PTH
649 nwritten = pth_write (fd, buf, nleft);
650 #else
651 nwritten = write (fd, buf, nleft);
652 #endif
653 if (nwritten < 0 && errno == EINTR)
654 continue;
655 if (nwritten < 0)
656 return -1;
657 nleft -= nwritten;
658 buf = (const char*)buf + nwritten;
660 return 0;
663 /* Read up to BUFLEN bytes from FD and return the number of bytes
664 actually read in NREAD. Returns -1 on error or 0 on success. */
665 static int
666 readn (int fd, void *buf, size_t buflen, size_t *nread)
668 size_t nleft = buflen;
669 int n;
670 /* void *orig_buf = buf; */
672 while (nleft > 0)
674 #ifdef USE_GNU_PTH
675 # ifdef HAVE_W32_SYSTEM
676 # error Cannot use pth_read here because it expects a system HANDLE.
677 # endif
678 n = pth_read (fd, buf, nleft);
679 #else
680 n = read (fd, buf, nleft);
681 #endif
682 if (n < 0 && errno == EINTR)
683 continue;
684 if (n < 0)
685 return -1; /* read error. */
686 if (!n)
687 break; /* EOF */
688 nleft -= n;
689 buf = (char*)buf + n;
691 if (nread)
692 *nread = buflen - nleft;
694 /* log_printhex (" readn:", orig_buf, *nread); */
696 return 0;
698 #endif /*NEED_PCSC_WRAPPER*/
700 static const char *
701 pcsc_error_string (long err)
703 const char *s;
705 if (!err)
706 return "okay";
707 if ((err & 0x80100000) != 0x80100000)
708 return "invalid PC/SC error code";
709 err &= 0xffff;
710 switch (err)
712 case 0x0002: s = "cancelled"; break;
713 case 0x000e: s = "can't dispose"; break;
714 case 0x0008: s = "insufficient buffer"; break;
715 case 0x0015: s = "invalid ATR"; break;
716 case 0x0003: s = "invalid handle"; break;
717 case 0x0004: s = "invalid parameter"; break;
718 case 0x0005: s = "invalid target"; break;
719 case 0x0011: s = "invalid value"; break;
720 case 0x0006: s = "no memory"; break;
721 case 0x0013: s = "comm error"; break;
722 case 0x0001: s = "internal error"; break;
723 case 0x0014: s = "unknown error"; break;
724 case 0x0007: s = "waited too long"; break;
725 case 0x0009: s = "unknown reader"; break;
726 case 0x000a: s = "timeout"; break;
727 case 0x000b: s = "sharing violation"; break;
728 case 0x000c: s = "no smartcard"; break;
729 case 0x000d: s = "unknown card"; break;
730 case 0x000f: s = "proto mismatch"; break;
731 case 0x0010: s = "not ready"; break;
732 case 0x0012: s = "system cancelled"; break;
733 case 0x0016: s = "not transacted"; break;
734 case 0x0017: s = "reader unavailable"; break;
735 case 0x0065: s = "unsupported card"; break;
736 case 0x0066: s = "unresponsive card"; break;
737 case 0x0067: s = "unpowered card"; break;
738 case 0x0068: s = "reset card"; break;
739 case 0x0069: s = "removed card"; break;
740 case 0x006a: s = "inserted card"; break;
741 case 0x001f: s = "unsupported feature"; break;
742 case 0x0019: s = "PCI too small"; break;
743 case 0x001a: s = "reader unsupported"; break;
744 case 0x001b: s = "duplicate reader"; break;
745 case 0x001c: s = "card unsupported"; break;
746 case 0x001d: s = "no service"; break;
747 case 0x001e: s = "service stopped"; break;
748 default: s = "unknown PC/SC error code"; break;
750 return s;
753 /* Map PC/SC error codes to our special host status words. */
754 static int
755 pcsc_error_to_sw (long ec)
757 int rc;
759 switch ( PCSC_ERR_MASK (ec) )
761 case 0: rc = 0; break;
763 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
764 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
765 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
766 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
767 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
768 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
770 case PCSC_E_INVALID_TARGET:
771 case PCSC_E_INVALID_VALUE:
772 case PCSC_E_INVALID_HANDLE:
773 case PCSC_E_INVALID_PARAMETER:
774 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
776 default: rc = SW_HOST_GENERAL_ERROR; break;
779 return rc;
782 static void
783 dump_pcsc_reader_status (int slot)
785 if (reader_table[slot].pcsc.card)
787 log_info ("reader slot %d: active protocol:", slot);
788 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
789 log_printf (" T0");
790 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
791 log_printf (" T1");
792 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
793 log_printf (" raw");
794 log_printf ("\n");
796 else
797 log_info ("reader slot %d: not connected\n", slot);
801 #ifndef NEED_PCSC_WRAPPER
802 static int
803 pcsc_get_status_direct (int slot, unsigned int *status)
805 long err;
806 struct pcsc_readerstate_s rdrstates[1];
808 memset (rdrstates, 0, sizeof *rdrstates);
809 rdrstates[0].reader = reader_table[slot].rdrname;
810 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
811 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
813 rdrstates, 1);
814 if (err == PCSC_E_TIMEOUT)
815 err = 0; /* Timeout is no error error here. */
816 if (err)
818 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
819 pcsc_error_string (err), err);
820 return pcsc_error_to_sw (err);
823 /* log_debug */
824 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
825 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
826 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
827 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
828 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
829 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
830 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
831 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
832 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
833 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
834 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
836 *status = 0;
837 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
838 *status |= APDU_CARD_PRESENT;
839 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
840 *status |= APDU_CARD_ACTIVE;
841 #ifndef HAVE_W32_SYSTEM
842 /* We indicate a useful card if it is not in use by another
843 application. This is because we only use exclusive access
844 mode. */
845 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
846 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
847 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
848 *status |= APDU_CARD_USABLE;
849 #else
850 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
851 time when we are the only user (SCM SCR335) under Windows. */
852 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
853 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
854 *status |= APDU_CARD_USABLE;
855 #endif
857 return 0;
859 #endif /*!NEED_PCSC_WRAPPER*/
862 #ifdef NEED_PCSC_WRAPPER
863 static int
864 pcsc_get_status_wrapped (int slot, unsigned int *status)
866 long err;
867 reader_table_t slotp;
868 size_t len, full_len;
869 int i, n;
870 unsigned char msgbuf[9];
871 unsigned char buffer[16];
872 int sw = SW_HOST_CARD_IO_ERROR;
874 slotp = reader_table + slot;
876 if (slotp->pcsc.req_fd == -1
877 || slotp->pcsc.rsp_fd == -1
878 || slotp->pcsc.pid == (pid_t)(-1) )
880 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
881 return sw;
884 msgbuf[0] = 0x04; /* STATUS command. */
885 len = 0;
886 msgbuf[1] = (len >> 24);
887 msgbuf[2] = (len >> 16);
888 msgbuf[3] = (len >> 8);
889 msgbuf[4] = (len );
890 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
892 log_error ("error sending PC/SC STATUS request: %s\n",
893 strerror (errno));
894 goto command_failed;
897 /* Read the response. */
898 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
900 log_error ("error receiving PC/SC STATUS response: %s\n",
901 i? strerror (errno) : "premature EOF");
902 goto command_failed;
904 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
905 if (msgbuf[0] != 0x81 || len < 4)
907 log_error ("invalid response header from PC/SC received\n");
908 goto command_failed;
910 len -= 4; /* Already read the error code. */
911 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
912 | (msgbuf[7] << 8 ) | msgbuf[8]);
913 if (err)
915 log_error ("pcsc_status failed: %s (0x%lx)\n",
916 pcsc_error_string (err), err);
917 /* This is a proper error code, so return immediately. */
918 return pcsc_error_to_sw (err);
921 full_len = len;
923 /* The current version returns 3 words but we allow also for old
924 versions returning only 2 words. */
925 n = 12 < len ? 12 : len;
926 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
927 || (len != 8 && len != 12))
929 log_error ("error receiving PC/SC STATUS response: %s\n",
930 i? strerror (errno) : "premature EOF");
931 goto command_failed;
934 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
937 full_len -= len;
938 /* Newer versions of the wrapper might send more status bytes.
939 Read them. */
940 while (full_len)
942 unsigned char dummybuf[128];
944 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
945 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
947 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
948 i? strerror (errno) : "premature EOF");
949 goto command_failed;
951 full_len -= n;
954 /* We are lucky: The wrapper already returns the data in the
955 required format. */
956 *status = buffer[3];
957 return 0;
959 command_failed:
960 close (slotp->pcsc.req_fd);
961 close (slotp->pcsc.rsp_fd);
962 slotp->pcsc.req_fd = -1;
963 slotp->pcsc.rsp_fd = -1;
964 kill (slotp->pcsc.pid, SIGTERM);
965 slotp->pcsc.pid = (pid_t)(-1);
966 slotp->used = 0;
967 return sw;
969 #endif /*NEED_PCSC_WRAPPER*/
972 static int
973 pcsc_get_status (int slot, unsigned int *status)
975 #ifdef NEED_PCSC_WRAPPER
976 return pcsc_get_status_wrapped (slot, status);
977 #else
978 return pcsc_get_status_direct (slot, status);
979 #endif
983 #ifndef NEED_PCSC_WRAPPER
984 static int
985 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
986 unsigned char *buffer, size_t *buflen,
987 struct pininfo_s *pininfo)
989 long err;
990 struct pcsc_io_request_s send_pci;
991 unsigned long recv_len;
993 if (!reader_table[slot].atrlen
994 && (err = reset_pcsc_reader (slot)))
995 return err;
997 if (DBG_CARD_IO)
998 log_printhex (" PCSC_data:", apdu, apdulen);
1000 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1001 send_pci.protocol = PCSC_PROTOCOL_T1;
1002 else
1003 send_pci.protocol = PCSC_PROTOCOL_T0;
1004 send_pci.pci_len = sizeof send_pci;
1005 recv_len = *buflen;
1006 err = pcsc_transmit (reader_table[slot].pcsc.card,
1007 &send_pci, apdu, apdulen,
1008 NULL, buffer, &recv_len);
1009 *buflen = recv_len;
1010 if (err)
1011 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1012 pcsc_error_string (err), err);
1014 return pcsc_error_to_sw (err);
1016 #endif /*!NEED_PCSC_WRAPPER*/
1019 #ifdef NEED_PCSC_WRAPPER
1020 static int
1021 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1022 unsigned char *buffer, size_t *buflen,
1023 struct pininfo_s *pininfo)
1025 long err;
1026 reader_table_t slotp;
1027 size_t len, full_len;
1028 int i, n;
1029 unsigned char msgbuf[9];
1030 int sw = SW_HOST_CARD_IO_ERROR;
1032 (void)pininfo;
1034 if (!reader_table[slot].atrlen
1035 && (err = reset_pcsc_reader (slot)))
1036 return err;
1038 if (DBG_CARD_IO)
1039 log_printhex (" PCSC_data:", apdu, apdulen);
1041 slotp = reader_table + slot;
1043 if (slotp->pcsc.req_fd == -1
1044 || slotp->pcsc.rsp_fd == -1
1045 || slotp->pcsc.pid == (pid_t)(-1) )
1047 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1048 return sw;
1051 msgbuf[0] = 0x03; /* TRANSMIT command. */
1052 len = apdulen;
1053 msgbuf[1] = (len >> 24);
1054 msgbuf[2] = (len >> 16);
1055 msgbuf[3] = (len >> 8);
1056 msgbuf[4] = (len );
1057 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1058 || writen (slotp->pcsc.req_fd, apdu, len))
1060 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1061 strerror (errno));
1062 goto command_failed;
1065 /* Read the response. */
1066 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1068 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1069 i? strerror (errno) : "premature EOF");
1070 goto command_failed;
1072 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1073 if (msgbuf[0] != 0x81 || len < 4)
1075 log_error ("invalid response header from PC/SC received\n");
1076 goto command_failed;
1078 len -= 4; /* Already read the error code. */
1079 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1080 | (msgbuf[7] << 8 ) | msgbuf[8]);
1081 if (err)
1083 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1084 pcsc_error_string (err), err);
1085 return pcsc_error_to_sw (err);
1088 full_len = len;
1090 n = *buflen < len ? *buflen : len;
1091 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1093 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1094 i? strerror (errno) : "premature EOF");
1095 goto command_failed;
1097 *buflen = n;
1099 full_len -= len;
1100 if (full_len)
1102 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1103 err = SW_HOST_INV_VALUE;
1105 /* We need to read any rest of the response, to keep the
1106 protocol running. */
1107 while (full_len)
1109 unsigned char dummybuf[128];
1111 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1112 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1114 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1115 i? strerror (errno) : "premature EOF");
1116 goto command_failed;
1118 full_len -= n;
1121 return err;
1123 command_failed:
1124 close (slotp->pcsc.req_fd);
1125 close (slotp->pcsc.rsp_fd);
1126 slotp->pcsc.req_fd = -1;
1127 slotp->pcsc.rsp_fd = -1;
1128 kill (slotp->pcsc.pid, SIGTERM);
1129 slotp->pcsc.pid = (pid_t)(-1);
1130 slotp->used = 0;
1131 return sw;
1133 #endif /*NEED_PCSC_WRAPPER*/
1136 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1137 *BUFLEN data in BUFFER, the actual returned size will be stored at
1138 BUFLEN. Returns: A status word. */
1139 static int
1140 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1141 unsigned char *buffer, size_t *buflen,
1142 struct pininfo_s *pininfo)
1144 #ifdef NEED_PCSC_WRAPPER
1145 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1146 #else
1147 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1148 #endif
1152 #ifndef NEED_PCSC_WRAPPER
1153 static int
1154 close_pcsc_reader_direct (int slot)
1156 pcsc_release_context (reader_table[slot].pcsc.context);
1157 xfree (reader_table[slot].rdrname);
1158 reader_table[slot].rdrname = NULL;
1159 reader_table[slot].used = 0;
1160 return 0;
1162 #endif /*!NEED_PCSC_WRAPPER*/
1165 #ifdef NEED_PCSC_WRAPPER
1166 static int
1167 close_pcsc_reader_wrapped (int slot)
1169 long err;
1170 reader_table_t slotp;
1171 size_t len;
1172 int i;
1173 unsigned char msgbuf[9];
1175 slotp = reader_table + slot;
1177 if (slotp->pcsc.req_fd == -1
1178 || slotp->pcsc.rsp_fd == -1
1179 || slotp->pcsc.pid == (pid_t)(-1) )
1181 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1182 return 0;
1185 msgbuf[0] = 0x02; /* CLOSE command. */
1186 len = 0;
1187 msgbuf[1] = (len >> 24);
1188 msgbuf[2] = (len >> 16);
1189 msgbuf[3] = (len >> 8);
1190 msgbuf[4] = (len );
1191 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1193 log_error ("error sending PC/SC CLOSE request: %s\n",
1194 strerror (errno));
1195 goto command_failed;
1198 /* Read the response. */
1199 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1201 log_error ("error receiving PC/SC CLOSE response: %s\n",
1202 i? strerror (errno) : "premature EOF");
1203 goto command_failed;
1205 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1206 if (msgbuf[0] != 0x81 || len < 4)
1208 log_error ("invalid response header from PC/SC received\n");
1209 goto command_failed;
1211 len -= 4; /* Already read the error code. */
1212 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1213 | (msgbuf[7] << 8 ) | msgbuf[8]);
1214 if (err)
1215 log_error ("pcsc_close failed: %s (0x%lx)\n",
1216 pcsc_error_string (err), err);
1218 /* We will close the wrapper in any case - errors are merely
1219 informational. */
1221 command_failed:
1222 close (slotp->pcsc.req_fd);
1223 close (slotp->pcsc.rsp_fd);
1224 slotp->pcsc.req_fd = -1;
1225 slotp->pcsc.rsp_fd = -1;
1226 kill (slotp->pcsc.pid, SIGTERM);
1227 slotp->pcsc.pid = (pid_t)(-1);
1228 slotp->used = 0;
1229 return 0;
1231 #endif /*NEED_PCSC_WRAPPER*/
1234 static int
1235 close_pcsc_reader (int slot)
1237 #ifdef NEED_PCSC_WRAPPER
1238 return close_pcsc_reader_wrapped (slot);
1239 #else
1240 return close_pcsc_reader_direct (slot);
1241 #endif
1245 /* Connect a PC/SC card. */
1246 #ifndef NEED_PCSC_WRAPPER
1247 static int
1248 connect_pcsc_card (int slot)
1250 long err;
1252 assert (slot >= 0 && slot < MAX_READER);
1254 if (reader_table[slot].pcsc.card)
1255 return SW_HOST_ALREADY_CONNECTED;
1257 reader_table[slot].atrlen = 0;
1258 reader_table[slot].last_status = 0;
1259 reader_table[slot].is_t0 = 0;
1261 err = pcsc_connect (reader_table[slot].pcsc.context,
1262 reader_table[slot].rdrname,
1263 PCSC_SHARE_EXCLUSIVE,
1264 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1265 &reader_table[slot].pcsc.card,
1266 &reader_table[slot].pcsc.protocol);
1267 if (err)
1269 reader_table[slot].pcsc.card = 0;
1270 if (err != PCSC_E_NO_SMARTCARD)
1271 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1272 pcsc_error_string (err), err);
1274 else
1276 char reader[250];
1277 unsigned long readerlen, atrlen;
1278 unsigned long card_state, card_protocol;
1280 atrlen = DIM (reader_table[0].atr);
1281 readerlen = sizeof reader -1 ;
1282 err = pcsc_status (reader_table[slot].pcsc.card,
1283 reader, &readerlen,
1284 &card_state, &card_protocol,
1285 reader_table[slot].atr, &atrlen);
1286 if (err)
1287 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1288 pcsc_error_string (err), err, readerlen);
1289 else
1291 if (atrlen > DIM (reader_table[0].atr))
1292 log_bug ("ATR returned by pcsc_status is too large\n");
1293 reader_table[slot].atrlen = atrlen;
1294 /* If we got to here we know that a card is present
1295 and usable. Remember this. */
1296 reader_table[slot].last_status = ( APDU_CARD_USABLE
1297 | APDU_CARD_PRESENT
1298 | APDU_CARD_ACTIVE);
1299 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1303 dump_reader_status (slot);
1304 return pcsc_error_to_sw (err);
1306 #endif /*!NEED_PCSC_WRAPPER*/
1309 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1310 is not connected. */
1311 #ifndef NEED_PCSC_WRAPPER
1312 static int
1313 disconnect_pcsc_card (int slot)
1315 long err;
1317 assert (slot >= 0 && slot < MAX_READER);
1319 if (!reader_table[slot].pcsc.card)
1320 return 0;
1322 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1323 if (err)
1325 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1326 pcsc_error_string (err), err);
1327 return SW_HOST_CARD_IO_ERROR;
1329 reader_table[slot].pcsc.card = 0;
1330 return 0;
1332 #endif /*!NEED_PCSC_WRAPPER*/
1335 #ifndef NEED_PCSC_WRAPPER
1336 static int
1337 reset_pcsc_reader_direct (int slot)
1339 int sw;
1341 sw = disconnect_pcsc_card (slot);
1342 if (!sw)
1343 sw = connect_pcsc_card (slot);
1345 return sw;
1347 #endif /*NEED_PCSC_WRAPPER*/
1350 #ifdef NEED_PCSC_WRAPPER
1351 static int
1352 reset_pcsc_reader_wrapped (int slot)
1354 long err;
1355 reader_table_t slotp;
1356 size_t len;
1357 int i, n;
1358 unsigned char msgbuf[9];
1359 unsigned int dummy_status;
1360 int sw = SW_HOST_CARD_IO_ERROR;
1362 slotp = reader_table + slot;
1364 if (slotp->pcsc.req_fd == -1
1365 || slotp->pcsc.rsp_fd == -1
1366 || slotp->pcsc.pid == (pid_t)(-1) )
1368 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1369 return sw;
1372 msgbuf[0] = 0x05; /* RESET command. */
1373 len = 0;
1374 msgbuf[1] = (len >> 24);
1375 msgbuf[2] = (len >> 16);
1376 msgbuf[3] = (len >> 8);
1377 msgbuf[4] = (len );
1378 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1380 log_error ("error sending PC/SC RESET request: %s\n",
1381 strerror (errno));
1382 goto command_failed;
1385 /* Read the response. */
1386 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1388 log_error ("error receiving PC/SC RESET response: %s\n",
1389 i? strerror (errno) : "premature EOF");
1390 goto command_failed;
1392 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1393 if (msgbuf[0] != 0x81 || len < 4)
1395 log_error ("invalid response header from PC/SC received\n");
1396 goto command_failed;
1398 len -= 4; /* Already read the error code. */
1399 if (len > DIM (slotp->atr))
1401 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1402 (unsigned long)len);
1403 sw = SW_HOST_GENERAL_ERROR;
1404 goto command_failed;
1406 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1407 | (msgbuf[7] << 8 ) | msgbuf[8]);
1408 if (err)
1410 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1411 pcsc_error_string (err), err);
1412 /* If the error code is no smart card, we should not considere
1413 this a major error and close the wrapper. */
1414 sw = pcsc_error_to_sw (err);
1415 if (err == PCSC_E_NO_SMARTCARD)
1416 return sw;
1417 goto command_failed;
1420 /* The open function may return a zero for the ATR length to
1421 indicate that no card is present. */
1422 n = len;
1423 if (n)
1425 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1427 log_error ("error receiving PC/SC RESET response: %s\n",
1428 i? strerror (errno) : "premature EOF");
1429 goto command_failed;
1432 slotp->atrlen = len;
1434 /* Read the status so that IS_T0 will be set. */
1435 pcsc_get_status (slot, &dummy_status);
1437 return 0;
1439 command_failed:
1440 close (slotp->pcsc.req_fd);
1441 close (slotp->pcsc.rsp_fd);
1442 slotp->pcsc.req_fd = -1;
1443 slotp->pcsc.rsp_fd = -1;
1444 kill (slotp->pcsc.pid, SIGTERM);
1445 slotp->pcsc.pid = (pid_t)(-1);
1446 slotp->used = 0;
1447 return sw;
1449 #endif /* !NEED_PCSC_WRAPPER */
1452 /* Send an PC/SC reset command and return a status word on error or 0
1453 on success. */
1454 static int
1455 reset_pcsc_reader (int slot)
1457 #ifdef NEED_PCSC_WRAPPER
1458 return reset_pcsc_reader_wrapped (slot);
1459 #else
1460 return reset_pcsc_reader_direct (slot);
1461 #endif
1465 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1466 error or a slot number for the reader. */
1467 #ifndef NEED_PCSC_WRAPPER
1468 static int
1469 open_pcsc_reader_direct (const char *portstr)
1471 long err;
1472 int slot;
1473 char *list = NULL;
1474 unsigned long nreader, listlen;
1475 char *p;
1477 slot = new_reader_slot ();
1478 if (slot == -1)
1479 return -1;
1481 /* Fixme: Allocating a context for each slot is not required. One
1482 global context should be sufficient. */
1483 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1484 &reader_table[slot].pcsc.context);
1485 if (err)
1487 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1488 pcsc_error_string (err), err);
1489 reader_table[slot].used = 0;
1490 return -1;
1493 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1494 NULL, NULL, &nreader);
1495 if (!err)
1497 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1498 if (!list)
1500 log_error ("error allocating memory for reader list\n");
1501 pcsc_release_context (reader_table[slot].pcsc.context);
1502 reader_table[slot].used = 0;
1503 return -1 /*SW_HOST_OUT_OF_CORE*/;
1505 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1506 NULL, list, &nreader);
1508 if (err)
1510 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1511 pcsc_error_string (err), err);
1512 pcsc_release_context (reader_table[slot].pcsc.context);
1513 reader_table[slot].used = 0;
1514 xfree (list);
1515 return -1;
1518 listlen = nreader;
1519 p = list;
1520 while (nreader)
1522 if (!*p && !p[1])
1523 break;
1524 if (*p)
1525 log_info ("detected reader `%s'\n", p);
1526 if (nreader < (strlen (p)+1))
1528 log_error ("invalid response from pcsc_list_readers\n");
1529 break;
1531 nreader -= strlen (p)+1;
1532 p += strlen (p) + 1;
1535 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1536 if (!reader_table[slot].rdrname)
1538 log_error ("error allocating memory for reader name\n");
1539 pcsc_release_context (reader_table[slot].pcsc.context);
1540 reader_table[slot].used = 0;
1541 return -1;
1543 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1544 xfree (list);
1545 list = NULL;
1547 reader_table[slot].pcsc.card = 0;
1548 reader_table[slot].atrlen = 0;
1549 reader_table[slot].last_status = 0;
1551 reader_table[slot].connect_card = connect_pcsc_card;
1552 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1553 reader_table[slot].close_reader = close_pcsc_reader;
1554 reader_table[slot].reset_reader = reset_pcsc_reader;
1555 reader_table[slot].get_status_reader = pcsc_get_status;
1556 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1557 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1559 dump_reader_status (slot);
1560 return slot;
1562 #endif /*!NEED_PCSC_WRAPPER */
1565 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1566 needed to cope with different thread models and other peculiarities
1567 of libpcsclite. */
1568 #ifdef NEED_PCSC_WRAPPER
1569 static int
1570 open_pcsc_reader_wrapped (const char *portstr)
1572 int slot;
1573 reader_table_t slotp;
1574 int fd, rp[2], wp[2];
1575 int n, i;
1576 pid_t pid;
1577 size_t len;
1578 unsigned char msgbuf[9];
1579 int err;
1580 unsigned int dummy_status;
1581 int sw = SW_HOST_CARD_IO_ERROR;
1582 /* Note that we use the constant and not the fucntion because this
1583 code won't be be used under Windows. */
1584 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1586 if (access (wrapperpgm, X_OK))
1588 log_error ("can't run PC/SC access module `%s': %s\n",
1589 wrapperpgm, strerror (errno));
1590 return -1;
1593 slot = new_reader_slot ();
1594 if (slot == -1)
1595 return -1;
1596 slotp = reader_table + slot;
1598 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
1599 the common directy but implement it directly so that this file
1600 may still be source copied. */
1602 if (pipe (rp) == -1)
1604 log_error ("error creating a pipe: %s\n", strerror (errno));
1605 slotp->used = 0;
1606 return -1;
1608 if (pipe (wp) == -1)
1610 log_error ("error creating a pipe: %s\n", strerror (errno));
1611 close (rp[0]);
1612 close (rp[1]);
1613 slotp->used = 0;
1614 return -1;
1617 pid = fork ();
1618 if (pid == -1)
1620 log_error ("error forking process: %s\n", strerror (errno));
1621 close (rp[0]);
1622 close (rp[1]);
1623 close (wp[0]);
1624 close (wp[1]);
1625 slotp->used = 0;
1626 return -1;
1628 slotp->pcsc.pid = pid;
1630 if (!pid)
1631 { /*
1632 === Child ===
1635 /* Double fork. */
1636 pid = fork ();
1637 if (pid == -1)
1638 _exit (31);
1639 if (pid)
1640 _exit (0); /* Immediate exit this parent, so that the child
1641 gets cleaned up by the init process. */
1643 /* Connect our pipes. */
1644 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1645 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1646 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1647 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1649 /* Send stderr to the bit bucket. */
1650 fd = open ("/dev/null", O_WRONLY);
1651 if (fd == -1)
1652 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1653 if (fd != 2 && dup2 (fd, 2) == -1)
1654 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1656 /* Close all other files. */
1657 close_all_fds (3, NULL);
1659 execl (wrapperpgm,
1660 "pcsc-wrapper",
1661 "--",
1662 "1", /* API version */
1663 opt.pcsc_driver, /* Name of the PC/SC library. */
1664 NULL);
1665 _exit (31);
1669 === Parent ===
1671 close (wp[0]);
1672 close (rp[1]);
1673 slotp->pcsc.req_fd = wp[1];
1674 slotp->pcsc.rsp_fd = rp[0];
1676 /* Wait for the intermediate child to terminate. */
1677 #ifdef USE_GNU_PTH
1678 #define WAIT pth_waitpid
1679 #else
1680 #define WAIT waitpid
1681 #endif
1682 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1684 #undef WAIT
1686 /* Now send the open request. */
1687 msgbuf[0] = 0x01; /* OPEN command. */
1688 len = portstr? strlen (portstr):0;
1689 msgbuf[1] = (len >> 24);
1690 msgbuf[2] = (len >> 16);
1691 msgbuf[3] = (len >> 8);
1692 msgbuf[4] = (len );
1693 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1694 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1696 log_error ("error sending PC/SC OPEN request: %s\n",
1697 strerror (errno));
1698 goto command_failed;
1700 /* Read the response. */
1701 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1703 log_error ("error receiving PC/SC OPEN response: %s\n",
1704 i? strerror (errno) : "premature EOF");
1705 goto command_failed;
1707 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1708 if (msgbuf[0] != 0x81 || len < 4)
1710 log_error ("invalid response header from PC/SC received\n");
1711 goto command_failed;
1713 len -= 4; /* Already read the error code. */
1714 if (len > DIM (slotp->atr))
1716 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1717 (unsigned long)len);
1718 goto command_failed;
1720 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1721 | (msgbuf[7] << 8 ) | msgbuf[8]);
1722 if (err)
1724 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1725 sw = pcsc_error_to_sw (err);
1726 goto command_failed;
1729 slotp->last_status = 0;
1731 /* The open request may return a zero for the ATR length to
1732 indicate that no card is present. */
1733 n = len;
1734 if (n)
1736 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1738 log_error ("error receiving PC/SC OPEN response: %s\n",
1739 i? strerror (errno) : "premature EOF");
1740 goto command_failed;
1742 /* If we got to here we know that a card is present
1743 and usable. Thus remember this. */
1744 slotp->last_status = ( APDU_CARD_USABLE
1745 | APDU_CARD_PRESENT
1746 | APDU_CARD_ACTIVE);
1748 slotp->atrlen = len;
1750 reader_table[slot].close_reader = close_pcsc_reader;
1751 reader_table[slot].reset_reader = reset_pcsc_reader;
1752 reader_table[slot].get_status_reader = pcsc_get_status;
1753 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1754 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1756 /* Read the status so that IS_T0 will be set. */
1757 pcsc_get_status (slot, &dummy_status);
1759 dump_reader_status (slot);
1760 return slot;
1762 command_failed:
1763 close (slotp->pcsc.req_fd);
1764 close (slotp->pcsc.rsp_fd);
1765 slotp->pcsc.req_fd = -1;
1766 slotp->pcsc.rsp_fd = -1;
1767 kill (slotp->pcsc.pid, SIGTERM);
1768 slotp->pcsc.pid = (pid_t)(-1);
1769 slotp->used = 0;
1770 /* There is no way to return SW. */
1771 return -1;
1774 #endif /*NEED_PCSC_WRAPPER*/
1777 static int
1778 open_pcsc_reader (const char *portstr)
1780 #ifdef NEED_PCSC_WRAPPER
1781 return open_pcsc_reader_wrapped (portstr);
1782 #else
1783 return open_pcsc_reader_direct (portstr);
1784 #endif
1789 #ifdef HAVE_LIBUSB
1791 Internal CCID driver interface.
1795 static void
1796 dump_ccid_reader_status (int slot)
1798 log_info ("reader slot %d: using ccid driver\n", slot);
1801 static int
1802 close_ccid_reader (int slot)
1804 ccid_close_reader (reader_table[slot].ccid.handle);
1805 reader_table[slot].used = 0;
1806 return 0;
1810 static int
1811 shutdown_ccid_reader (int slot)
1813 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1814 return 0;
1818 static int
1819 reset_ccid_reader (int slot)
1821 int err;
1822 reader_table_t slotp = reader_table + slot;
1823 unsigned char atr[33];
1824 size_t atrlen;
1826 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1827 if (err)
1828 return err;
1829 /* If the reset was successful, update the ATR. */
1830 assert (sizeof slotp->atr >= sizeof atr);
1831 slotp->atrlen = atrlen;
1832 memcpy (slotp->atr, atr, atrlen);
1833 dump_reader_status (slot);
1834 return 0;
1838 static int
1839 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1841 reader_table_t slotp = reader_table + slot;
1843 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1847 static int
1848 get_status_ccid (int slot, unsigned int *status)
1850 int rc;
1851 int bits;
1853 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1854 if (rc)
1855 return rc;
1857 if (bits == 0)
1858 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1859 else if (bits == 1)
1860 *status = APDU_CARD_PRESENT;
1861 else
1862 *status = 0;
1864 return 0;
1868 /* Actually send the APDU of length APDULEN to SLOT and return a
1869 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1870 set to BUFLEN. Returns: Internal CCID driver error code. */
1871 static int
1872 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1873 unsigned char *buffer, size_t *buflen,
1874 struct pininfo_s *pininfo)
1876 long err;
1877 size_t maxbuflen;
1879 /* If we don't have an ATR, we need to reset the reader first. */
1880 if (!reader_table[slot].atrlen
1881 && (err = reset_ccid_reader (slot)))
1882 return err;
1884 if (DBG_CARD_IO)
1885 log_printhex (" raw apdu:", apdu, apdulen);
1887 maxbuflen = *buflen;
1888 if (pininfo)
1889 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1890 apdu, apdulen,
1891 pininfo->mode,
1892 pininfo->minlen,
1893 pininfo->maxlen,
1894 pininfo->padlen,
1895 buffer, maxbuflen, buflen);
1896 else
1897 err = ccid_transceive (reader_table[slot].ccid.handle,
1898 apdu, apdulen,
1899 buffer, maxbuflen, buflen);
1900 if (err)
1901 log_error ("ccid_transceive failed: (0x%lx)\n",
1902 err);
1904 return err;
1908 /* Check whether the CCID reader supports the ISO command code COMMAND
1909 on the keypad. Return 0 on success. For a description of the pin
1910 parameters, see ccid-driver.c */
1911 static int
1912 check_ccid_keypad (int slot, int command, int pin_mode,
1913 int pinlen_min, int pinlen_max, int pin_padlen)
1915 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1917 apdu[1] = command;
1918 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1919 apdu, sizeof apdu,
1920 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1921 NULL, 0, NULL);
1925 /* Open the reader and try to read an ATR. */
1926 static int
1927 open_ccid_reader (const char *portstr)
1929 int err;
1930 int slot;
1931 reader_table_t slotp;
1933 slot = new_reader_slot ();
1934 if (slot == -1)
1935 return -1;
1936 slotp = reader_table + slot;
1938 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1939 if (err)
1941 slotp->used = 0;
1942 return -1;
1945 err = ccid_get_atr (slotp->ccid.handle,
1946 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1947 if (err)
1949 slotp->atrlen = 0;
1950 err = 0;
1952 else
1954 /* If we got to here we know that a card is present
1955 and usable. Thus remember this. */
1956 reader_table[slot].last_status = (APDU_CARD_USABLE
1957 | APDU_CARD_PRESENT
1958 | APDU_CARD_ACTIVE);
1961 reader_table[slot].close_reader = close_ccid_reader;
1962 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1963 reader_table[slot].reset_reader = reset_ccid_reader;
1964 reader_table[slot].get_status_reader = get_status_ccid;
1965 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1966 reader_table[slot].check_keypad = check_ccid_keypad;
1967 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1968 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
1969 /* Our CCID reader code does not support T=0 at all, thus reset the
1970 flag. */
1971 reader_table[slot].is_t0 = 0;
1973 dump_reader_status (slot);
1974 return slot;
1979 #endif /* HAVE_LIBUSB */
1983 #ifdef USE_G10CODE_RAPDU
1985 The Remote APDU Interface.
1987 This uses the Remote APDU protocol to contact a reader.
1989 The port number is actually an index into the list of ports as
1990 returned via the protocol.
1994 static int
1995 rapdu_status_to_sw (int status)
1997 int rc;
1999 switch (status)
2001 case RAPDU_STATUS_SUCCESS: rc = 0; break;
2003 case RAPDU_STATUS_INVCMD:
2004 case RAPDU_STATUS_INVPROT:
2005 case RAPDU_STATUS_INVSEQ:
2006 case RAPDU_STATUS_INVCOOKIE:
2007 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
2009 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
2010 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2011 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2012 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2013 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2014 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2016 default: rc = SW_HOST_GENERAL_ERROR; break;
2019 return rc;
2024 static int
2025 close_rapdu_reader (int slot)
2027 rapdu_release (reader_table[slot].rapdu.handle);
2028 reader_table[slot].used = 0;
2029 return 0;
2033 static int
2034 reset_rapdu_reader (int slot)
2036 int err;
2037 reader_table_t slotp;
2038 rapdu_msg_t msg = NULL;
2040 slotp = reader_table + slot;
2042 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2043 if (err)
2045 log_error ("sending rapdu command RESET failed: %s\n",
2046 err < 0 ? strerror (errno): rapdu_strerror (err));
2047 rapdu_msg_release (msg);
2048 return rapdu_status_to_sw (err);
2050 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2051 if (err)
2053 log_error ("receiving rapdu message failed: %s\n",
2054 err < 0 ? strerror (errno): rapdu_strerror (err));
2055 rapdu_msg_release (msg);
2056 return rapdu_status_to_sw (err);
2058 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2060 int sw = rapdu_status_to_sw (msg->cmd);
2061 log_error ("rapdu command RESET failed: %s\n",
2062 rapdu_strerror (msg->cmd));
2063 rapdu_msg_release (msg);
2064 return sw;
2066 if (msg->datalen > DIM (slotp->atr))
2068 log_error ("ATR returned by the RAPDU layer is too large\n");
2069 rapdu_msg_release (msg);
2070 return SW_HOST_INV_VALUE;
2072 slotp->atrlen = msg->datalen;
2073 memcpy (slotp->atr, msg->data, msg->datalen);
2075 rapdu_msg_release (msg);
2076 return 0;
2080 static int
2081 my_rapdu_get_status (int slot, unsigned int *status)
2083 int err;
2084 reader_table_t slotp;
2085 rapdu_msg_t msg = NULL;
2086 int oldslot;
2088 slotp = reader_table + slot;
2090 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2091 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2092 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2093 if (err)
2095 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2096 err < 0 ? strerror (errno): rapdu_strerror (err));
2097 return rapdu_status_to_sw (err);
2099 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2100 if (err)
2102 log_error ("receiving rapdu message failed: %s\n",
2103 err < 0 ? strerror (errno): rapdu_strerror (err));
2104 rapdu_msg_release (msg);
2105 return rapdu_status_to_sw (err);
2107 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2109 int sw = rapdu_status_to_sw (msg->cmd);
2110 log_error ("rapdu command GET_STATUS failed: %s\n",
2111 rapdu_strerror (msg->cmd));
2112 rapdu_msg_release (msg);
2113 return sw;
2115 *status = msg->data[0];
2117 rapdu_msg_release (msg);
2118 return 0;
2122 /* Actually send the APDU of length APDULEN to SLOT and return a
2123 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2124 set to BUFLEN. Returns: APDU error code. */
2125 static int
2126 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2127 unsigned char *buffer, size_t *buflen,
2128 struct pininfo_s *pininfo)
2130 int err;
2131 reader_table_t slotp;
2132 rapdu_msg_t msg = NULL;
2133 size_t maxlen = *buflen;
2135 slotp = reader_table + slot;
2137 *buflen = 0;
2138 if (DBG_CARD_IO)
2139 log_printhex (" APDU_data:", apdu, apdulen);
2141 if (apdulen < 4)
2143 log_error ("rapdu_send_apdu: APDU is too short\n");
2144 return SW_HOST_INV_VALUE;
2147 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2148 if (err)
2150 log_error ("sending rapdu command APDU failed: %s\n",
2151 err < 0 ? strerror (errno): rapdu_strerror (err));
2152 rapdu_msg_release (msg);
2153 return rapdu_status_to_sw (err);
2155 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2156 if (err)
2158 log_error ("receiving rapdu message failed: %s\n",
2159 err < 0 ? strerror (errno): rapdu_strerror (err));
2160 rapdu_msg_release (msg);
2161 return rapdu_status_to_sw (err);
2163 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2165 int sw = rapdu_status_to_sw (msg->cmd);
2166 log_error ("rapdu command APDU failed: %s\n",
2167 rapdu_strerror (msg->cmd));
2168 rapdu_msg_release (msg);
2169 return sw;
2172 if (msg->datalen > maxlen)
2174 log_error ("rapdu response apdu too large\n");
2175 rapdu_msg_release (msg);
2176 return SW_HOST_INV_VALUE;
2179 *buflen = msg->datalen;
2180 memcpy (buffer, msg->data, msg->datalen);
2182 rapdu_msg_release (msg);
2183 return 0;
2186 static int
2187 open_rapdu_reader (int portno,
2188 const unsigned char *cookie, size_t length,
2189 int (*readfnc) (void *opaque,
2190 void *buffer, size_t size),
2191 void *readfnc_value,
2192 int (*writefnc) (void *opaque,
2193 const void *buffer, size_t size),
2194 void *writefnc_value,
2195 void (*closefnc) (void *opaque),
2196 void *closefnc_value)
2198 int err;
2199 int slot;
2200 reader_table_t slotp;
2201 rapdu_msg_t msg = NULL;
2203 slot = new_reader_slot ();
2204 if (slot == -1)
2205 return -1;
2206 slotp = reader_table + slot;
2208 slotp->rapdu.handle = rapdu_new ();
2209 if (!slotp->rapdu.handle)
2211 slotp->used = 0;
2212 return -1;
2215 rapdu_set_reader (slotp->rapdu.handle, portno);
2217 rapdu_set_iofunc (slotp->rapdu.handle,
2218 readfnc, readfnc_value,
2219 writefnc, writefnc_value,
2220 closefnc, closefnc_value);
2221 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2223 /* First try to get the current ATR, but if the card is inactive
2224 issue a reset instead. */
2225 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2226 if (err == RAPDU_STATUS_NEEDRESET)
2227 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2228 if (err)
2230 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2231 err < 0 ? strerror (errno): rapdu_strerror (err));
2232 goto failure;
2234 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2235 if (err)
2237 log_info ("receiving rapdu message failed: %s\n",
2238 err < 0 ? strerror (errno): rapdu_strerror (err));
2239 goto failure;
2241 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2243 log_info ("rapdu command GET ATR failed: %s\n",
2244 rapdu_strerror (msg->cmd));
2245 goto failure;
2247 if (msg->datalen > DIM (slotp->atr))
2249 log_error ("ATR returned by the RAPDU layer is too large\n");
2250 goto failure;
2252 slotp->atrlen = msg->datalen;
2253 memcpy (slotp->atr, msg->data, msg->datalen);
2255 reader_table[slot].close_reader = close_rapdu_reader;
2256 reader_table[slot].reset_reader = reset_rapdu_reader;
2257 reader_table[slot].get_status_reader = my_rapdu_get_status;
2258 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2259 reader_table[slot].check_keypad = NULL;
2260 reader_table[slot].dump_status_reader = NULL;
2262 dump_reader_status (slot);
2263 rapdu_msg_release (msg);
2264 return slot;
2266 failure:
2267 rapdu_msg_release (msg);
2268 rapdu_release (slotp->rapdu.handle);
2269 slotp->used = 0;
2270 return -1;
2273 #endif /*USE_G10CODE_RAPDU*/
2278 Driver Access
2282 static int
2283 lock_slot (int slot)
2285 #ifdef USE_GNU_PTH
2286 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2288 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2289 return SW_HOST_LOCKING_FAILED;
2291 #endif /*USE_GNU_PTH*/
2292 return 0;
2295 static int
2296 trylock_slot (int slot)
2298 #ifdef USE_GNU_PTH
2299 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2301 if (errno == EBUSY)
2302 return SW_HOST_BUSY;
2303 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2304 return SW_HOST_LOCKING_FAILED;
2306 #endif /*USE_GNU_PTH*/
2307 return 0;
2310 static void
2311 unlock_slot (int slot)
2313 #ifdef USE_GNU_PTH
2314 if (!pth_mutex_release (&reader_table[slot].lock))
2315 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2316 #endif /*USE_GNU_PTH*/
2320 /* Open the reader and return an internal slot number or -1 on
2321 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2322 the first USB reader. For PC/SC the first listed reader). */
2324 apdu_open_reader (const char *portstr)
2326 static int pcsc_api_loaded, ct_api_loaded;
2328 #ifdef HAVE_LIBUSB
2329 if (!opt.disable_ccid)
2331 int slot, i;
2332 const char *s;
2334 slot = open_ccid_reader (portstr);
2335 if (slot != -1)
2336 return slot; /* got one */
2338 /* If a CCID reader specification has been given, the user does
2339 not want a fallback to other drivers. */
2340 if (portstr)
2341 for (s=portstr, i=0; *s; s++)
2342 if (*s == ':' && (++i == 3))
2343 return -1;
2346 #endif /* HAVE_LIBUSB */
2348 if (opt.ctapi_driver && *opt.ctapi_driver)
2350 int port = portstr? atoi (portstr) : 32768;
2352 if (!ct_api_loaded)
2354 void *handle;
2356 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2357 if (!handle)
2359 log_error ("apdu_open_reader: failed to open driver: %s\n",
2360 dlerror ());
2361 return -1;
2363 CT_init = dlsym (handle, "CT_init");
2364 CT_data = dlsym (handle, "CT_data");
2365 CT_close = dlsym (handle, "CT_close");
2366 if (!CT_init || !CT_data || !CT_close)
2368 log_error ("apdu_open_reader: invalid CT-API driver\n");
2369 dlclose (handle);
2370 return -1;
2372 ct_api_loaded = 1;
2374 return open_ct_reader (port);
2378 /* No ctAPI configured, so lets try the PC/SC API */
2379 if (!pcsc_api_loaded)
2381 #ifndef NEED_PCSC_WRAPPER
2382 void *handle;
2384 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2385 if (!handle)
2387 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2388 opt.pcsc_driver, dlerror ());
2389 return -1;
2392 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2393 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2394 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2395 #if defined(_WIN32) || defined(__CYGWIN__)
2396 if (!pcsc_list_readers)
2397 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2398 #endif
2399 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2400 #if defined(_WIN32) || defined(__CYGWIN__)
2401 if (!pcsc_get_status_change)
2402 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2403 #endif
2404 pcsc_connect = dlsym (handle, "SCardConnect");
2405 #if defined(_WIN32) || defined(__CYGWIN__)
2406 if (!pcsc_connect)
2407 pcsc_connect = dlsym (handle, "SCardConnectA");
2408 #endif
2409 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2410 #if defined(_WIN32) || defined(__CYGWIN__)
2411 if (!pcsc_reconnect)
2412 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2413 #endif
2414 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2415 pcsc_status = dlsym (handle, "SCardStatus");
2416 #if defined(_WIN32) || defined(__CYGWIN__)
2417 if (!pcsc_status)
2418 pcsc_status = dlsym (handle, "SCardStatusA");
2419 #endif
2420 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2421 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2422 pcsc_transmit = dlsym (handle, "SCardTransmit");
2423 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2425 if (!pcsc_establish_context
2426 || !pcsc_release_context
2427 || !pcsc_list_readers
2428 || !pcsc_get_status_change
2429 || !pcsc_connect
2430 || !pcsc_reconnect
2431 || !pcsc_disconnect
2432 || !pcsc_status
2433 || !pcsc_begin_transaction
2434 || !pcsc_end_transaction
2435 || !pcsc_transmit
2436 /* || !pcsc_set_timeout */)
2438 /* Note that set_timeout is currently not used and also not
2439 available under Windows. */
2440 log_error ("apdu_open_reader: invalid PC/SC driver "
2441 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2442 !!pcsc_establish_context,
2443 !!pcsc_release_context,
2444 !!pcsc_list_readers,
2445 !!pcsc_get_status_change,
2446 !!pcsc_connect,
2447 !!pcsc_reconnect,
2448 !!pcsc_disconnect,
2449 !!pcsc_status,
2450 !!pcsc_begin_transaction,
2451 !!pcsc_end_transaction,
2452 !!pcsc_transmit,
2453 !!pcsc_set_timeout );
2454 dlclose (handle);
2455 return -1;
2457 #endif /*!NEED_PCSC_WRAPPER*/
2458 pcsc_api_loaded = 1;
2461 return open_pcsc_reader (portstr);
2465 /* Open an remote reader and return an internal slot number or -1 on
2466 error. This function is an alternative to apdu_open_reader and used
2467 with remote readers only. Note that the supplied CLOSEFNC will
2468 only be called once and the slot will not be valid afther this.
2470 If PORTSTR is NULL we default to the first availabe port.
2473 apdu_open_remote_reader (const char *portstr,
2474 const unsigned char *cookie, size_t length,
2475 int (*readfnc) (void *opaque,
2476 void *buffer, size_t size),
2477 void *readfnc_value,
2478 int (*writefnc) (void *opaque,
2479 const void *buffer, size_t size),
2480 void *writefnc_value,
2481 void (*closefnc) (void *opaque),
2482 void *closefnc_value)
2484 #ifdef USE_G10CODE_RAPDU
2485 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2486 cookie, length,
2487 readfnc, readfnc_value,
2488 writefnc, writefnc_value,
2489 closefnc, closefnc_value);
2490 #else
2491 (void)portstr;
2492 (void)cookie;
2493 (void)length;
2494 (void)readfnc;
2495 (void)readfnc_value;
2496 (void)writefnc;
2497 (void)writefnc_value;
2498 (void)closefnc;
2499 (void)closefnc_value;
2500 #ifdef _WIN32
2501 errno = ENOENT;
2502 #else
2503 errno = ENOSYS;
2504 #endif
2505 return -1;
2506 #endif
2511 apdu_close_reader (int slot)
2513 int sw;
2515 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2516 return SW_HOST_NO_DRIVER;
2517 sw = apdu_disconnect (slot);
2518 if (sw)
2519 return sw;
2520 if (reader_table[slot].close_reader)
2521 return reader_table[slot].close_reader (slot);
2522 return SW_HOST_NOT_SUPPORTED;
2526 /* Function suitable for a cleanup function to close all reader. It
2527 should not be used if the reader will be opened again. The reason
2528 for implementing this to properly close USB devices so that they
2529 will startup the next time without error. */
2530 void
2531 apdu_prepare_exit (void)
2533 static int sentinel;
2534 int slot;
2536 if (!sentinel)
2538 sentinel = 1;
2539 for (slot = 0; slot < MAX_READER; slot++)
2540 if (reader_table[slot].used)
2542 apdu_disconnect (slot);
2543 if (reader_table[slot].close_reader)
2544 reader_table[slot].close_reader (slot);
2545 reader_table[slot].used = 0;
2547 sentinel = 0;
2552 /* Shutdown a reader; that is basically the same as a close but keeps
2553 the handle ready for later use. A apdu_reset_reader or apdu_connect
2554 should be used to get it active again. */
2556 apdu_shutdown_reader (int slot)
2558 int sw;
2560 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2561 return SW_HOST_NO_DRIVER;
2562 sw = apdu_disconnect (slot);
2563 if (sw)
2564 return sw;
2565 if (reader_table[slot].shutdown_reader)
2566 return reader_table[slot].shutdown_reader (slot);
2567 return SW_HOST_NOT_SUPPORTED;
2570 /* Enumerate all readers and return information on whether this reader
2571 is in use. The caller should start with SLOT set to 0 and
2572 increment it with each call until an error is returned. */
2574 apdu_enum_reader (int slot, int *used)
2576 if (slot < 0 || slot >= MAX_READER)
2577 return SW_HOST_NO_DRIVER;
2578 *used = reader_table[slot].used;
2579 return 0;
2583 /* Connect a card. This is used to power up the card and make sure
2584 that an ATR is available. */
2586 apdu_connect (int slot)
2588 int sw;
2590 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2591 return SW_HOST_NO_DRIVER;
2593 /* Only if the access method provides a connect function we use it.
2594 If not, we expect that the card has been implicitly connected by
2595 apdu_open_reader. */
2596 if (reader_table[slot].connect_card)
2598 sw = lock_slot (slot);
2599 if (!sw)
2601 sw = reader_table[slot].connect_card (slot);
2602 unlock_slot (slot);
2605 else
2606 sw = 0;
2608 /* We need to call apdu_get_status_internal, so that the last-status
2609 machinery gets setup properly even if a card is inserted while
2610 scdaemon is fired up and apdu_get_status has not yet been called.
2611 Without that we would force a reset of the card with the next
2612 call to apdu_get_status. */
2613 apdu_get_status_internal (slot, 1, 1, NULL, NULL);
2615 return sw;
2620 apdu_disconnect (int slot)
2622 int sw;
2624 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2625 return SW_HOST_NO_DRIVER;
2627 if (reader_table[slot].disconnect_card)
2629 sw = lock_slot (slot);
2630 if (!sw)
2632 sw = reader_table[slot].disconnect_card (slot);
2633 unlock_slot (slot);
2636 else
2637 sw = 0;
2638 return sw;
2642 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
2643 CB is NULL the progress callback is removed. */
2645 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2647 int sw;
2649 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2650 return SW_HOST_NO_DRIVER;
2652 if (reader_table[slot].set_progress_cb)
2654 sw = lock_slot (slot);
2655 if (!sw)
2657 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2658 unlock_slot (slot);
2661 else
2662 sw = 0;
2663 return sw;
2667 /* Do a reset for the card in reader at SLOT. */
2669 apdu_reset (int slot)
2671 int sw;
2673 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2674 return SW_HOST_NO_DRIVER;
2676 if ((sw = lock_slot (slot)))
2677 return sw;
2679 reader_table[slot].last_status = 0;
2680 if (reader_table[slot].reset_reader)
2681 sw = reader_table[slot].reset_reader (slot);
2683 if (!sw)
2685 /* If we got to here we know that a card is present
2686 and usable. Thus remember this. */
2687 reader_table[slot].last_status = (APDU_CARD_USABLE
2688 | APDU_CARD_PRESENT
2689 | APDU_CARD_ACTIVE);
2692 unlock_slot (slot);
2693 return sw;
2697 /* Activate a card if it has not yet been done. This is a kind of
2698 reset-if-required. It is useful to test for presence of a card
2699 before issuing a bunch of apdu commands. It does not wait on a
2700 locked card. */
2702 apdu_activate (int slot)
2704 int sw;
2705 unsigned int s;
2707 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2708 return SW_HOST_NO_DRIVER;
2710 if ((sw = trylock_slot (slot)))
2711 return sw;
2713 if (reader_table[slot].get_status_reader)
2714 sw = reader_table[slot].get_status_reader (slot, &s);
2716 if (!sw)
2718 if (!(s & 2)) /* Card not present. */
2719 sw = SW_HOST_NO_CARD;
2720 else if ( ((s & 2) && !(s & 4))
2721 || !reader_table[slot].atrlen )
2723 /* We don't have an ATR or a card is present though inactive:
2724 do a reset now. */
2725 if (reader_table[slot].reset_reader)
2727 reader_table[slot].last_status = 0;
2728 sw = reader_table[slot].reset_reader (slot);
2729 if (!sw)
2731 /* If we got to here we know that a card is present
2732 and usable. Thus remember this. */
2733 reader_table[slot].last_status = (APDU_CARD_USABLE
2734 | APDU_CARD_PRESENT
2735 | APDU_CARD_ACTIVE);
2741 unlock_slot (slot);
2742 return sw;
2746 unsigned char *
2747 apdu_get_atr (int slot, size_t *atrlen)
2749 unsigned char *buf;
2751 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2752 return NULL;
2753 if (!reader_table[slot].atrlen)
2754 return NULL;
2755 buf = xtrymalloc (reader_table[slot].atrlen);
2756 if (!buf)
2757 return NULL;
2758 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2759 *atrlen = reader_table[slot].atrlen;
2760 return buf;
2765 /* Retrieve the status for SLOT. The function does only wait for the
2766 card to become available if HANG is set to true. On success the
2767 bits in STATUS will be set to
2769 APDU_CARD_USABLE (bit 0) = card present and usable
2770 APDU_CARD_PRESENT (bit 1) = card present
2771 APDU_CARD_ACTIVE (bit 2) = card active
2772 (bit 3) = card access locked [not yet implemented]
2774 For must applications, testing bit 0 is sufficient.
2776 CHANGED will receive the value of the counter tracking the number
2777 of card insertions. This value may be used to detect a card
2778 change.
2780 static int
2781 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
2782 unsigned int *status, unsigned int *changed)
2784 int sw;
2785 unsigned int s;
2787 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2788 return SW_HOST_NO_DRIVER;
2790 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2791 return sw;
2793 if (reader_table[slot].get_status_reader)
2794 sw = reader_table[slot].get_status_reader (slot, &s);
2796 unlock_slot (slot);
2798 if (sw)
2800 reader_table[slot].last_status = 0;
2801 return sw;
2804 /* Keep track of changes. */
2805 if (s != reader_table[slot].last_status
2806 || !reader_table[slot].any_status )
2808 reader_table[slot].change_counter++;
2809 /* Make sure that the ATR is invalid so that a reset will be
2810 triggered by apdu_activate. */
2811 if (!no_atr_reset)
2812 reader_table[slot].atrlen = 0;
2814 reader_table[slot].any_status = 1;
2815 reader_table[slot].last_status = s;
2817 if (status)
2818 *status = s;
2819 if (changed)
2820 *changed = reader_table[slot].change_counter;
2821 return 0;
2825 /* See above for a description. */
2827 apdu_get_status (int slot, int hang,
2828 unsigned int *status, unsigned int *changed)
2830 return apdu_get_status_internal (slot, hang, 0, status, changed);
2834 /* Check whether the reader supports the ISO command code COMMAND on
2835 the keypad. Return 0 on success. For a description of the pin
2836 parameters, see ccid-driver.c */
2838 apdu_check_keypad (int slot, int command, int pin_mode,
2839 int pinlen_min, int pinlen_max, int pin_padlen)
2841 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2842 return SW_HOST_NO_DRIVER;
2844 if (reader_table[slot].check_keypad)
2845 return reader_table[slot].check_keypad (slot, command,
2846 pin_mode, pinlen_min, pinlen_max,
2847 pin_padlen);
2848 else
2849 return SW_HOST_NOT_SUPPORTED;
2853 /* Dispatcher for the actual send_apdu function. Note, that this
2854 function should be called in locked state. */
2855 static int
2856 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2857 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2859 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2860 return SW_HOST_NO_DRIVER;
2862 if (reader_table[slot].send_apdu_reader)
2863 return reader_table[slot].send_apdu_reader (slot,
2864 apdu, apdulen,
2865 buffer, buflen,
2866 pininfo);
2867 else
2868 return SW_HOST_NOT_SUPPORTED;
2872 /* Core APDU tranceiver function. Parameters are described at
2873 apdu_send_le with the exception of PININFO which indicates keypad
2874 related operations if not NULL. If EXTENDED_MODE is not 0
2875 command chaining or extended length will be used according to these
2876 values:
2877 n < 0 := Use command chaining with the data part limited to -n
2878 in each chunk. If -1 is used a default value is used.
2879 n == 0 := No extended mode or command chaining.
2880 n == 1 := Use extended length for input and output without a
2881 length limit.
2882 n > 1 := Use extended length with up to N bytes.
2885 static int
2886 send_le (int slot, int class, int ins, int p0, int p1,
2887 int lc, const char *data, int le,
2888 unsigned char **retbuf, size_t *retbuflen,
2889 struct pininfo_s *pininfo, int extended_mode)
2891 #define SHORT_RESULT_BUFFER_SIZE 258
2892 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
2893 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2894 unsigned char *result_buffer = NULL;
2895 size_t result_buffer_size;
2896 unsigned char *result;
2897 size_t resultlen;
2898 unsigned char short_apdu_buffer[5+256+1];
2899 unsigned char *apdu_buffer = NULL;
2900 size_t apdu_buffer_size;
2901 unsigned char *apdu;
2902 size_t apdulen;
2903 int sw;
2904 long rc; /* We need a long here due to PC/SC. */
2905 int did_exact_length_hack = 0;
2906 int use_chaining = 0;
2907 int use_extended_length = 0;
2908 int lc_chunk;
2910 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2911 return SW_HOST_NO_DRIVER;
2913 if (DBG_CARD_IO)
2914 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2915 class, ins, p0, p1, lc, le, extended_mode);
2917 if (lc != -1 && (lc > 255 || lc < 0))
2919 /* Data does not fit into an APDU. What we do now depends on
2920 the EXTENDED_MODE parameter. */
2921 if (!extended_mode)
2922 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2923 else if (extended_mode > 0)
2924 use_extended_length = 1;
2925 else if (extended_mode < 0)
2927 /* Send APDU using chaining mode. */
2928 if (lc > 16384)
2929 return SW_WRONG_LENGTH; /* Sanity check. */
2930 if ((class&0xf0) != 0)
2931 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2932 use_chaining = extended_mode == -1? 255 : -extended_mode;
2933 use_chaining &= 0xff;
2935 else
2936 return SW_HOST_INV_VALUE;
2938 else if (lc == -1 && extended_mode > 0)
2939 use_extended_length = 1;
2941 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2943 /* Expected Data does not fit into an APDU. What we do now
2944 depends on the EXTENDED_MODE parameter. Note that a check
2945 for command chaining does not make sense because we are
2946 looking at Le. */
2947 if (!extended_mode)
2948 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2949 else if (use_extended_length)
2950 ; /* We are already using extended length. */
2951 else if (extended_mode > 0)
2952 use_extended_length = 1;
2953 else
2954 return SW_HOST_INV_VALUE;
2957 if ((!data && lc != -1) || (data && lc == -1))
2958 return SW_HOST_INV_VALUE;
2960 if (use_extended_length)
2962 if (reader_table[slot].is_t0)
2963 return SW_HOST_NOT_SUPPORTED;
2965 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2966 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2967 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2968 if (!apdu_buffer)
2969 return SW_HOST_OUT_OF_CORE;
2970 apdu = apdu_buffer;
2972 else
2974 apdu_buffer_size = sizeof short_apdu_buffer;
2975 apdu = short_apdu_buffer;
2978 if (use_extended_length && (le > 256 || le < 0))
2980 result_buffer_size = le < 0? 4096 : le;
2981 result_buffer = xtrymalloc (result_buffer_size + 10);
2982 if (!result_buffer)
2984 xfree (apdu_buffer);
2985 return SW_HOST_OUT_OF_CORE;
2987 result = result_buffer;
2989 else
2991 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2992 result = short_result_buffer;
2994 #undef SHORT_RESULT_BUFFER_SIZE
2996 if ((sw = lock_slot (slot)))
2998 xfree (apdu_buffer);
2999 xfree (result_buffer);
3000 return sw;
3005 if (use_extended_length)
3007 use_chaining = 0;
3008 apdulen = 0;
3009 apdu[apdulen++] = class;
3010 apdu[apdulen++] = ins;
3011 apdu[apdulen++] = p0;
3012 apdu[apdulen++] = p1;
3013 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3014 if (lc >= 0)
3016 apdu[apdulen++] = ((lc >> 8) & 0xff);
3017 apdu[apdulen++] = (lc & 0xff);
3018 memcpy (apdu+apdulen, data, lc);
3019 data += lc;
3020 apdulen += lc;
3022 if (le != -1)
3024 apdu[apdulen++] = ((le >> 8) & 0xff);
3025 apdu[apdulen++] = (le & 0xff);
3028 else
3030 apdulen = 0;
3031 apdu[apdulen] = class;
3032 if (use_chaining && lc > 255)
3034 apdu[apdulen] |= 0x10;
3035 assert (use_chaining < 256);
3036 lc_chunk = use_chaining;
3037 lc -= use_chaining;
3039 else
3041 use_chaining = 0;
3042 lc_chunk = lc;
3044 apdulen++;
3045 apdu[apdulen++] = ins;
3046 apdu[apdulen++] = p0;
3047 apdu[apdulen++] = p1;
3048 if (lc_chunk != -1)
3050 apdu[apdulen++] = lc_chunk;
3051 memcpy (apdu+apdulen, data, lc_chunk);
3052 data += lc_chunk;
3053 apdulen += lc_chunk;
3054 /* T=0 does not allow the use of Lc together with Le;
3055 thus disable Le in this case. */
3056 if (reader_table[slot].is_t0)
3057 le = -1;
3059 if (le != -1 && !use_chaining)
3060 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3063 exact_length_hack:
3064 /* As a safeguard don't pass any garbage to the driver. */
3065 assert (apdulen <= apdu_buffer_size);
3066 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3067 resultlen = result_buffer_size;
3068 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3069 if (rc || resultlen < 2)
3071 log_info ("apdu_send_simple(%d) failed: %s\n",
3072 slot, apdu_strerror (rc));
3073 unlock_slot (slot);
3074 xfree (apdu_buffer);
3075 xfree (result_buffer);
3076 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3078 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3079 if (!use_extended_length
3080 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3082 apdu[apdulen-1] = (sw & 0x00ff);
3083 did_exact_length_hack = 1;
3084 goto exact_length_hack;
3087 while (use_chaining && sw == SW_SUCCESS);
3089 if (apdu_buffer)
3091 xfree (apdu_buffer);
3092 apdu_buffer = NULL;
3093 apdu_buffer_size = 0;
3096 /* Store away the returned data but strip the statusword. */
3097 resultlen -= 2;
3098 if (DBG_CARD_IO)
3100 log_debug (" response: sw=%04X datalen=%d\n",
3101 sw, (unsigned int)resultlen);
3102 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3103 log_printhex (" dump: ", result, resultlen);
3106 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3108 if (retbuf)
3110 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3111 if (!*retbuf)
3113 unlock_slot (slot);
3114 xfree (result_buffer);
3115 return SW_HOST_OUT_OF_CORE;
3117 *retbuflen = resultlen;
3118 memcpy (*retbuf, result, resultlen);
3121 else if ((sw & 0xff00) == SW_MORE_DATA)
3123 unsigned char *p = NULL, *tmp;
3124 size_t bufsize = 4096;
3126 /* It is likely that we need to return much more data, so we
3127 start off with a large buffer. */
3128 if (retbuf)
3130 *retbuf = p = xtrymalloc (bufsize);
3131 if (!*retbuf)
3133 unlock_slot (slot);
3134 xfree (result_buffer);
3135 return SW_HOST_OUT_OF_CORE;
3137 assert (resultlen < bufsize);
3138 memcpy (p, result, resultlen);
3139 p += resultlen;
3144 int len = (sw & 0x00ff);
3146 if (DBG_CARD_IO)
3147 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3148 slot, len);
3149 apdu_buffer_size = sizeof short_apdu_buffer;
3150 apdu = short_apdu_buffer;
3151 apdulen = 0;
3152 apdu[apdulen++] = class;
3153 apdu[apdulen++] = 0xC0;
3154 apdu[apdulen++] = 0;
3155 apdu[apdulen++] = 0;
3156 apdu[apdulen++] = len;
3157 assert (apdulen <= apdu_buffer_size);
3158 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3159 resultlen = result_buffer_size;
3160 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3161 if (rc || resultlen < 2)
3163 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3164 slot, apdu_strerror (rc));
3165 unlock_slot (slot);
3166 xfree (result_buffer);
3167 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3169 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3170 resultlen -= 2;
3171 if (DBG_CARD_IO)
3173 log_debug (" more: sw=%04X datalen=%d\n",
3174 sw, (unsigned int)resultlen);
3175 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3176 log_printhex (" dump: ", result, resultlen);
3179 if ((sw & 0xff00) == SW_MORE_DATA
3180 || sw == SW_SUCCESS
3181 || sw == SW_EOF_REACHED )
3183 if (retbuf && resultlen)
3185 if (p - *retbuf + resultlen > bufsize)
3187 bufsize += resultlen > 4096? resultlen: 4096;
3188 tmp = xtryrealloc (*retbuf, bufsize);
3189 if (!tmp)
3191 unlock_slot (slot);
3192 xfree (result_buffer);
3193 return SW_HOST_OUT_OF_CORE;
3195 p = tmp + (p - *retbuf);
3196 *retbuf = tmp;
3198 memcpy (p, result, resultlen);
3199 p += resultlen;
3202 else
3203 log_info ("apdu_send_simple(%d) "
3204 "got unexpected status %04X from get response\n",
3205 slot, sw);
3207 while ((sw & 0xff00) == SW_MORE_DATA);
3209 if (retbuf)
3211 *retbuflen = p - *retbuf;
3212 tmp = xtryrealloc (*retbuf, *retbuflen);
3213 if (tmp)
3214 *retbuf = tmp;
3218 unlock_slot (slot);
3219 xfree (result_buffer);
3221 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3222 log_printhex (" dump: ", *retbuf, *retbuflen);
3224 return sw;
3227 /* Send an APDU to the card in SLOT. The APDU is created from all
3228 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
3229 for LC won't sent this field and the data field; in this case DATA
3230 must also be passed as NULL. If EXTENDED_MODE is not 0 command
3231 chaining or extended length will be used; see send_le for details.
3232 The return value is the status word or -1 for an invalid SLOT or
3233 other non card related error. If RETBUF is not NULL, it will
3234 receive an allocated buffer with the returned data. The length of
3235 that data will be put into *RETBUFLEN. The caller is reponsible
3236 for releasing the buffer even in case of errors. */
3238 apdu_send_le(int slot, int extended_mode,
3239 int class, int ins, int p0, int p1,
3240 int lc, const char *data, int le,
3241 unsigned char **retbuf, size_t *retbuflen)
3243 return send_le (slot, class, ins, p0, p1,
3244 lc, data, le,
3245 retbuf, retbuflen,
3246 NULL, extended_mode);
3250 /* Send an APDU to the card in SLOT. The APDU is created from all
3251 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3252 LC won't sent this field and the data field; in this case DATA must
3253 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3254 or extended length will be used; see send_le for details. The
3255 return value is the status word or -1 for an invalid SLOT or other
3256 non card related error. If RETBUF is not NULL, it will receive an
3257 allocated buffer with the returned data. The length of that data
3258 will be put into *RETBUFLEN. The caller is reponsible for
3259 releasing the buffer even in case of errors. */
3261 apdu_send (int slot, int extended_mode,
3262 int class, int ins, int p0, int p1,
3263 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
3265 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3266 retbuf, retbuflen, NULL, extended_mode);
3269 /* Send an APDU to the card in SLOT. The APDU is created from all
3270 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3271 LC won't sent this field and the data field; in this case DATA must
3272 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3273 or extended length will be used; see send_le for details. The
3274 return value is the status word or -1 for an invalid SLOT or other
3275 non card related error. No data will be returned. */
3277 apdu_send_simple (int slot, int extended_mode,
3278 int class, int ins, int p0, int p1,
3279 int lc, const char *data)
3281 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3282 extended_mode);
3286 /* Same as apdu_send_simple but uses the keypad of the reader. */
3288 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
3289 int lc, const char *data,
3290 int pin_mode,
3291 int pinlen_min, int pinlen_max, int pin_padlen)
3293 struct pininfo_s pininfo;
3295 pininfo.mode = pin_mode;
3296 pininfo.minlen = pinlen_min;
3297 pininfo.maxlen = pinlen_max;
3298 pininfo.padlen = pin_padlen;
3299 return send_le (slot, class, ins, p0, p1, lc, data, -1,
3300 NULL, NULL, &pininfo, 0);
3304 /* This is a more generic version of the apdu sending routine. It
3305 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3306 and returns with an APDU including the status word. With
3307 HANDLE_MORE set to true this function will handle the MORE DATA
3308 status and return all APDUs concatenated with one status word at
3309 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
3310 with a max. result data length of EXTENDED_LENGTH bytes. The
3311 function does not return a regular status word but 0 on success.
3312 If the slot is locked, the function returns immediately with an
3313 error. */
3315 apdu_send_direct (int slot, size_t extended_length,
3316 const unsigned char *apdudata, size_t apdudatalen,
3317 int handle_more,
3318 unsigned char **retbuf, size_t *retbuflen)
3320 #define SHORT_RESULT_BUFFER_SIZE 258
3321 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3322 unsigned char *result_buffer = NULL;
3323 size_t result_buffer_size;
3324 unsigned char *result;
3325 size_t resultlen;
3326 unsigned char short_apdu_buffer[5+256+10];
3327 unsigned char *apdu_buffer = NULL;
3328 unsigned char *apdu;
3329 size_t apdulen;
3330 int sw;
3331 long rc; /* we need a long here due to PC/SC. */
3332 int class;
3334 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3335 return SW_HOST_NO_DRIVER;
3337 if (apdudatalen > 65535)
3338 return SW_HOST_INV_VALUE;
3340 if (apdudatalen > sizeof short_apdu_buffer - 5)
3342 apdu_buffer = xtrymalloc (apdudatalen + 5);
3343 if (!apdu_buffer)
3344 return SW_HOST_OUT_OF_CORE;
3345 apdu = apdu_buffer;
3347 else
3349 apdu = short_apdu_buffer;
3351 apdulen = apdudatalen;
3352 memcpy (apdu, apdudata, apdudatalen);
3353 class = apdulen? *apdu : 0;
3355 if (extended_length >= 256 && extended_length <= 65536)
3357 result_buffer_size = extended_length;
3358 result_buffer = xtrymalloc (result_buffer_size + 10);
3359 if (!result_buffer)
3361 xfree (apdu_buffer);
3362 return SW_HOST_OUT_OF_CORE;
3364 result = result_buffer;
3366 else
3368 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3369 result = short_result_buffer;
3371 #undef SHORT_RESULT_BUFFER_SIZE
3373 if ((sw = trylock_slot (slot)))
3375 xfree (apdu_buffer);
3376 xfree (result_buffer);
3377 return sw;
3380 resultlen = result_buffer_size;
3381 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3382 xfree (apdu_buffer);
3383 apdu_buffer = NULL;
3384 if (rc || resultlen < 2)
3386 log_error ("apdu_send_direct(%d) failed: %s\n",
3387 slot, apdu_strerror (rc));
3388 unlock_slot (slot);
3389 xfree (result_buffer);
3390 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3392 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3393 /* Store away the returned data but strip the statusword. */
3394 resultlen -= 2;
3395 if (DBG_CARD_IO)
3397 log_debug (" response: sw=%04X datalen=%d\n",
3398 sw, (unsigned int)resultlen);
3399 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3400 log_printhex (" dump: ", result, resultlen);
3403 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3405 unsigned char *p = NULL, *tmp;
3406 size_t bufsize = 4096;
3408 /* It is likely that we need to return much more data, so we
3409 start off with a large buffer. */
3410 if (retbuf)
3412 *retbuf = p = xtrymalloc (bufsize + 2);
3413 if (!*retbuf)
3415 unlock_slot (slot);
3416 xfree (result_buffer);
3417 return SW_HOST_OUT_OF_CORE;
3419 assert (resultlen < bufsize);
3420 memcpy (p, result, resultlen);
3421 p += resultlen;
3426 int len = (sw & 0x00ff);
3428 if (DBG_CARD_IO)
3429 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3430 slot, len);
3431 apdu = short_apdu_buffer;
3432 apdulen = 0;
3433 apdu[apdulen++] = class;
3434 apdu[apdulen++] = 0xC0;
3435 apdu[apdulen++] = 0;
3436 apdu[apdulen++] = 0;
3437 apdu[apdulen++] = len;
3438 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3439 resultlen = result_buffer_size;
3440 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3441 if (rc || resultlen < 2)
3443 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3444 slot, apdu_strerror (rc));
3445 unlock_slot (slot);
3446 xfree (result_buffer);
3447 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3449 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3450 resultlen -= 2;
3451 if (DBG_CARD_IO)
3453 log_debug (" more: sw=%04X datalen=%d\n",
3454 sw, (unsigned int)resultlen);
3455 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3456 log_printhex (" dump: ", result, resultlen);
3459 if ((sw & 0xff00) == SW_MORE_DATA
3460 || sw == SW_SUCCESS
3461 || sw == SW_EOF_REACHED )
3463 if (retbuf && resultlen)
3465 if (p - *retbuf + resultlen > bufsize)
3467 bufsize += resultlen > 4096? resultlen: 4096;
3468 tmp = xtryrealloc (*retbuf, bufsize + 2);
3469 if (!tmp)
3471 unlock_slot (slot);
3472 xfree (result_buffer);
3473 return SW_HOST_OUT_OF_CORE;
3475 p = tmp + (p - *retbuf);
3476 *retbuf = tmp;
3478 memcpy (p, result, resultlen);
3479 p += resultlen;
3482 else
3483 log_info ("apdu_send_direct(%d) "
3484 "got unexpected status %04X from get response\n",
3485 slot, sw);
3487 while ((sw & 0xff00) == SW_MORE_DATA);
3489 if (retbuf)
3491 *retbuflen = p - *retbuf;
3492 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3493 if (tmp)
3494 *retbuf = tmp;
3497 else
3499 if (retbuf)
3501 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3502 if (!*retbuf)
3504 unlock_slot (slot);
3505 xfree (result_buffer);
3506 return SW_HOST_OUT_OF_CORE;
3508 *retbuflen = resultlen;
3509 memcpy (*retbuf, result, resultlen);
3513 unlock_slot (slot);
3514 xfree (result_buffer);
3516 /* Append the status word. Note that we reserved the two extra
3517 bytes while allocating the buffer. */
3518 if (retbuf)
3520 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3521 (*retbuf)[(*retbuflen)++] = sw;
3524 if (DBG_CARD_IO && retbuf)
3525 log_printhex (" dump: ", *retbuf, *retbuflen);
3527 return 0;