1
/* apdu.c - ISO 7816 APDU functions and low level I/O
2
* Copyright (C) 2003, 2004 Free Software Foundation, Inc.
4
* This file is part of GnuPG.
6
* GnuPG is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; either version 2 of the License, or
9
* (at your option) any later version.
11
* GnuPG is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
* GNU General Public License for more details.
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20
* $Id: apdu.c,v 1.17 2004/10/28 09:06:50 wk Exp $
36
# include <opensc/opensc.h>
42
/* If requested include the definitions for the remote APDU protocol
44
#ifdef USE_G10CODE_RAPDU
46
#endif /*USE_G10CODE_RAPDU*/
48
#if defined(GNUPG_SCD_MAIN_HEADER)
49
#include GNUPG_SCD_MAIN_HEADER
50
#elif GNUPG_MAJOR_VERSION == 1
51
/* This is used with GnuPG version < 1.9. The code has been source
52
copied from the current GnuPG >= 1.9 and is maintained over
60
#else /* GNUPG_MAJOR_VERSION != 1 */
62
#endif /* GNUPG_MAJOR_VERSION != 1 */
66
#include "ccid-driver.h"
69
#define NEED_PCSC_WRAPPER 1
73
#define MAX_READER 4 /* Number of readers we support concurrently. */
77
#define DLSTDCALL __stdcall
82
#ifdef _POSIX_OPEN_MAX
83
#define MAX_OPEN_FDS _POSIX_OPEN_MAX
85
#define MAX_OPEN_FDS 20
89
/* A structure to collect information pertaining to one reader
91
struct reader_table_s {
92
int used; /* True if slot is used. */
93
unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
95
/* Function pointers intialized to the various backends. */
96
int (*close_reader)(int);
97
int (*shutdown_reader)(int);
98
int (*reset_reader)(int);
99
int (*get_status_reader)(int, unsigned int *);
100
int (*send_apdu_reader)(int,unsigned char *,size_t,
101
unsigned char *, size_t *);
102
void (*dump_status_reader)(int);
105
ccid_driver_t handle;
108
unsigned long context;
110
unsigned long protocol;
111
#ifdef NEED_PCSC_WRAPPER
115
#endif /*NEED_PCSC_WRAPPER*/
119
struct sc_context *ctx;
120
struct sc_card *scard;
122
#endif /*HAVE_OPENSC*/
123
#ifdef USE_G10CODE_RAPDU
127
#endif /*USE_G10CODE_RAPDU*/
128
char *rdrname; /* Name of the connected reader or NULL if unknown. */
131
unsigned char atr[33];
132
size_t atrlen; /* A zero length indicates that the ATR has
133
not yet been read; i.e. the card is not
135
unsigned int change_counter;
137
int lock_initialized;
141
typedef struct reader_table_s *reader_table_t;
143
/* A global table to keep track of active readers. */
144
static struct reader_table_s reader_table[MAX_READER];
147
/* ct API function pointer. */
148
static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
149
static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
150
unsigned char *sad, unsigned short lc,
151
unsigned char *cmd, unsigned short *lr,
153
static char (* DLSTDCALL CT_close) (unsigned short ctn);
155
/* PC/SC constants and function pointer. */
156
#define PCSC_SCOPE_USER 0
157
#define PCSC_SCOPE_TERMINAL 1
158
#define PCSC_SCOPE_SYSTEM 2
159
#define PCSC_SCOPE_GLOBAL 3
161
#define PCSC_PROTOCOL_T0 1
162
#define PCSC_PROTOCOL_T1 2
163
#define PCSC_PROTOCOL_RAW 4
165
#define PCSC_SHARE_EXCLUSIVE 1
166
#define PCSC_SHARE_SHARED 2
167
#define PCSC_SHARE_DIRECT 3
169
#define PCSC_LEAVE_CARD 0
170
#define PCSC_RESET_CARD 1
171
#define PCSC_UNPOWER_CARD 2
172
#define PCSC_EJECT_CARD 3
174
#define PCSC_UNKNOWN 0x0001
175
#define PCSC_ABSENT 0x0002 /* Card is absent. */
176
#define PCSC_PRESENT 0x0004 /* Card is present. */
177
#define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
178
#define PCSC_POWERED 0x0010 /* Card is powered. */
179
#define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
180
#define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
182
#define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
183
#define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
184
#define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
185
#define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
186
#define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
187
#define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
188
#define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
189
#define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
190
#define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
191
#define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
192
#define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
195
struct pcsc_io_request_s
197
unsigned long protocol;
198
unsigned long pci_len;
201
typedef struct pcsc_io_request_s *pcsc_io_request_t;
203
struct pcsc_readerstate_s
207
unsigned long current_state;
208
unsigned long event_state;
209
unsigned long atrlen;
210
unsigned char atr[33];
213
typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
215
long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
216
const void *reserved1,
217
const void *reserved2,
218
unsigned long *r_context);
219
long (* DLSTDCALL pcsc_release_context) (unsigned long context);
220
long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
222
char *readers, unsigned long*readerslen);
223
long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
224
unsigned long timeout,
225
pcsc_readerstate_t readerstates,
226
unsigned long nreaderstates);
227
long (* DLSTDCALL pcsc_connect) (unsigned long context,
229
unsigned long share_mode,
230
unsigned long preferred_protocols,
231
unsigned long *r_card,
232
unsigned long *r_active_protocol);
233
long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
234
unsigned long share_mode,
235
unsigned long preferred_protocols,
236
unsigned long initialization,
237
unsigned long *r_active_protocol);
238
long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
239
unsigned long disposition);
240
long (* DLSTDCALL pcsc_status) (unsigned long card,
241
char *reader, unsigned long *readerlen,
242
unsigned long *r_state,
243
unsigned long *r_protocol,
244
unsigned char *atr, unsigned long *atrlen);
245
long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
246
long (* DLSTDCALL pcsc_end_transaction) (unsigned long card);
247
long (* DLSTDCALL pcsc_transmit) (unsigned long card,
248
const pcsc_io_request_t send_pci,
249
const unsigned char *send_buffer,
250
unsigned long send_len,
251
pcsc_io_request_t recv_pci,
252
unsigned char *recv_buffer,
253
unsigned long *recv_len);
254
long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
255
unsigned long timeout);
265
/* Find an unused reader slot for PORTSTR and put it into the reader
266
table. Return -1 on error or the index into the reader table. */
268
new_reader_slot (void)
272
for (i=0; i < MAX_READER; i++)
274
if (!reader_table[i].used && reader == -1)
279
log_error ("new_reader_slot: out of slots\n");
283
if (!reader_table[reader].lock_initialized)
285
if (!pth_mutex_init (&reader_table[reader].lock))
287
log_error ("error initializing mutex: %s\n", strerror (errno));
290
reader_table[reader].lock_initialized = 1;
292
#endif /*USE_GNU_PTH*/
293
reader_table[reader].close_reader = NULL;
294
reader_table[reader].shutdown_reader = NULL;
295
reader_table[reader].reset_reader = NULL;
296
reader_table[reader].get_status_reader = NULL;
297
reader_table[reader].send_apdu_reader = NULL;
298
reader_table[reader].dump_status_reader = NULL;
300
reader_table[reader].used = 1;
301
reader_table[reader].last_status = 0;
302
#ifdef NEED_PCSC_WRAPPER
303
reader_table[reader].pcsc.req_fd = -1;
304
reader_table[reader].pcsc.rsp_fd = -1;
305
reader_table[reader].pcsc.pid = (pid_t)(-1);
313
dump_reader_status (int slot)
318
if (reader_table[slot].dump_status_reader)
319
reader_table[slot].dump_status_reader (slot);
321
if (reader_table[slot].status != -1
322
&& reader_table[slot].atrlen)
324
log_info ("slot %d: ATR=", slot);
325
log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
332
host_sw_string (long err)
336
case 0: return "okay";
337
case SW_HOST_OUT_OF_CORE: return "out of core";
338
case SW_HOST_INV_VALUE: return "invalid value";
339
case SW_HOST_NO_DRIVER: return "no driver";
340
case SW_HOST_NOT_SUPPORTED: return "not supported";
341
case SW_HOST_LOCKING_FAILED: return "locking failed";
342
case SW_HOST_BUSY: return "busy";
343
case SW_HOST_NO_CARD: return "no card";
344
case SW_HOST_CARD_INACTIVE: return "card inactive";
345
case SW_HOST_CARD_IO_ERROR: return "card I/O error";
346
case SW_HOST_GENERAL_ERROR: return "general error";
347
case SW_HOST_NO_READER: return "no reader";
348
case SW_HOST_ABORTED: return "aborted";
349
default: return "unknown host status error";
355
apdu_strerror (int rc)
359
case SW_EOF_REACHED : return "eof reached";
360
case SW_EEPROM_FAILURE : return "eeprom failure";
361
case SW_WRONG_LENGTH : return "wrong length";
362
case SW_CHV_WRONG : return "CHV wrong";
363
case SW_CHV_BLOCKED : return "CHV blocked";
364
case SW_USE_CONDITIONS : return "use conditions not satisfied";
365
case SW_BAD_PARAMETER : return "bad parameter";
366
case SW_NOT_SUPPORTED : return "not supported";
367
case SW_FILE_NOT_FOUND : return "file not found";
368
case SW_RECORD_NOT_FOUND:return "record not found";
369
case SW_REF_NOT_FOUND : return "reference not found";
370
case SW_BAD_P0_P1 : return "bad P0 or P1";
371
case SW_INS_NOT_SUP : return "instruction not supported";
372
case SW_CLA_NOT_SUP : return "class not supported";
373
case SW_SUCCESS : return "success";
375
if ((rc & ~0x00ff) == SW_MORE_DATA)
376
return "more data available";
377
if ( (rc & 0x10000) )
378
return host_sw_string (rc);
379
return "unknown status error";
390
ct_error_string (long err)
394
case 0: return "okay";
395
case -1: return "invalid data";
396
case -8: return "ct error";
397
case -10: return "transmission error";
398
case -11: return "memory allocation error";
399
case -128: return "HTSI error";
400
default: return "unknown CT-API error";
406
ct_dump_reader_status (int slot)
408
log_info ("reader slot %d: %s\n", slot,
409
reader_table[slot].status == 1? "Processor ICC present" :
410
reader_table[slot].status == 0? "Memory ICC present" :
415
/* Wait for the card in SLOT and activate it. Return a status word
416
error or 0 on success. */
418
ct_activate_card (int slot)
421
unsigned char dad[1], sad[1], cmd[11], buf[256];
422
unsigned short buflen;
424
/* Check whether card has been inserted. */
425
dad[0] = 1; /* Destination address: CT. */
426
sad[0] = 2; /* Source address: Host. */
428
cmd[0] = 0x20; /* Class byte. */
429
cmd[1] = 0x13; /* Request status. */
430
cmd[2] = 0x00; /* From kernel. */
431
cmd[3] = 0x80; /* Return card's DO. */
436
rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
437
if (rc || buflen < 2 || buf[buflen-2] != 0x90)
439
log_error ("ct_activate_card: can't get status of reader %d: %s\n",
440
slot, ct_error_string (rc));
441
return SW_HOST_CARD_IO_ERROR;
444
/* Connected, now activate the card. */
445
dad[0] = 1; /* Destination address: CT. */
446
sad[0] = 2; /* Source address: Host. */
448
cmd[0] = 0x20; /* Class byte. */
449
cmd[1] = 0x12; /* Request ICC. */
450
cmd[2] = 0x01; /* From first interface. */
451
cmd[3] = 0x01; /* Return card's ATR. */
456
rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
457
if (rc || buflen < 2 || buf[buflen-2] != 0x90)
459
log_error ("ct_activate_card(%d): activation failed: %s\n",
460
slot, ct_error_string (rc));
462
log_printhex (" received data:", buf, buflen);
463
return SW_HOST_CARD_IO_ERROR;
466
/* Store the type and the ATR. */
467
if (buflen - 2 > DIM (reader_table[0].atr))
469
log_error ("ct_activate_card(%d): ATR too long\n", slot);
470
return SW_HOST_CARD_IO_ERROR;
473
reader_table[slot].status = buf[buflen - 1];
474
memcpy (reader_table[slot].atr, buf, buflen - 2);
475
reader_table[slot].atrlen = buflen - 2;
481
close_ct_reader (int slot)
484
reader_table[slot].used = 0;
489
reset_ct_reader (int slot)
491
/* FIXME: Check is this is sufficient do do a reset. */
492
return ct_activate_card (slot);
497
ct_get_status (int slot, unsigned int *status)
499
*status = 1|2|4; /* FIXME */
502
return SW_HOST_NOT_SUPPORTED;
505
/* Actually send the APDU of length APDULEN to SLOT and return a
506
maximum of *BUFLEN data in BUFFER, the actual retruned size will be
507
set to BUFLEN. Returns: CT API error code. */
509
ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
510
unsigned char *buffer, size_t *buflen)
513
unsigned char dad[1], sad[1];
514
unsigned short ctbuflen;
516
/* If we don't have an ATR, we need to reset the reader first. */
517
if (!reader_table[slot].atrlen
518
&& (rc = reset_ct_reader (slot)))
521
dad[0] = 0; /* Destination address: Card. */
522
sad[0] = 2; /* Source address: Host. */
525
log_printhex (" CT_data:", apdu, apdulen);
526
rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
529
return rc? SW_HOST_CARD_IO_ERROR: 0;
534
/* Open a reader and return an internal handle for it. PORT is a
535
non-negative value with the port number of the reader. USB readers
536
do have port numbers starting at 32769. */
538
open_ct_reader (int port)
542
if (port < 0 || port > 0xffff)
544
log_error ("open_ct_reader: invalid port %d requested\n", port);
547
reader = new_reader_slot ();
550
reader_table[reader].port = port;
552
rc = CT_init (reader, (unsigned short)port);
555
log_error ("apdu_open_ct_reader failed on port %d: %s\n",
556
port, ct_error_string (rc));
557
reader_table[reader].used = 0;
561
/* Only try to activate the card. */
562
rc = ct_activate_card (reader);
565
reader_table[reader].atrlen = 0;
569
reader_table[reader].close_reader = close_ct_reader;
570
reader_table[reader].reset_reader = reset_ct_reader;
571
reader_table[reader].get_status_reader = ct_get_status;
572
reader_table[reader].send_apdu_reader = ct_send_apdu;
573
reader_table[reader].dump_status_reader = ct_dump_reader_status;
575
dump_reader_status (reader);
580
#ifdef NEED_PCSC_WRAPPER
582
writen (int fd, const void *buf, size_t nbytes)
584
size_t nleft = nbytes;
587
/* log_printhex (" writen:", buf, nbytes); */
592
nwritten = pth_write (fd, buf, nleft);
594
nwritten = write (fd, buf, nleft);
596
if (nwritten < 0 && errno == EINTR)
601
buf = (const char*)buf + nwritten;
606
/* Read up to BUFLEN bytes from FD and return the number of bytes
607
actually read in NREAD. Returns -1 on error or 0 on success. */
609
readn (int fd, void *buf, size_t buflen, size_t *nread)
611
size_t nleft = buflen;
613
/* void *orig_buf = buf; */
618
n = pth_read (fd, buf, nleft);
620
n = read (fd, buf, nleft);
622
if (n < 0 && errno == EINTR)
625
return -1; /* read error. */
629
buf = (char*)buf + n;
632
*nread = buflen - nleft;
634
/* log_printhex (" readn:", orig_buf, *nread); */
638
#endif /*NEED_PCSC_WRAPPER*/
641
pcsc_error_string (long err)
647
if ((err & 0x80100000) != 0x80100000)
648
return "invalid PC/SC error code";
652
case 0x0002: s = "cancelled"; break;
653
case 0x000e: s = "can't dispose"; break;
654
case 0x0008: s = "insufficient buffer"; break;
655
case 0x0015: s = "invalid ATR"; break;
656
case 0x0003: s = "invalid handle"; break;
657
case 0x0004: s = "invalid parameter"; break;
658
case 0x0005: s = "invalid target"; break;
659
case 0x0011: s = "invalid value"; break;
660
case 0x0006: s = "no memory"; break;
661
case 0x0013: s = "comm error"; break;
662
case 0x0001: s = "internal error"; break;
663
case 0x0014: s = "unknown error"; break;
664
case 0x0007: s = "waited too long"; break;
665
case 0x0009: s = "unknown reader"; break;
666
case 0x000a: s = "timeout"; break;
667
case 0x000b: s = "sharing violation"; break;
668
case 0x000c: s = "no smartcard"; break;
669
case 0x000d: s = "unknown card"; break;
670
case 0x000f: s = "proto mismatch"; break;
671
case 0x0010: s = "not ready"; break;
672
case 0x0012: s = "system cancelled"; break;
673
case 0x0016: s = "not transacted"; break;
674
case 0x0017: s = "reader unavailable"; break;
675
case 0x0065: s = "unsupported card"; break;
676
case 0x0066: s = "unresponsive card"; break;
677
case 0x0067: s = "unpowered card"; break;
678
case 0x0068: s = "reset card"; break;
679
case 0x0069: s = "removed card"; break;
680
case 0x006a: s = "inserted card"; break;
681
case 0x001f: s = "unsupported feature"; break;
682
case 0x0019: s = "PCI too small"; break;
683
case 0x001a: s = "reader unsupported"; break;
684
case 0x001b: s = "duplicate reader"; break;
685
case 0x001c: s = "card unsupported"; break;
686
case 0x001d: s = "no service"; break;
687
case 0x001e: s = "service stopped"; break;
688
default: s = "unknown PC/SC error code"; break;
698
dump_pcsc_reader_status (int slot)
700
log_info ("reader slot %d: active protocol:", slot);
701
if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
703
else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
705
else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
712
reset_pcsc_reader (int slot)
714
#ifdef NEED_PCSC_WRAPPER
716
reader_table_t slotp;
719
unsigned char msgbuf[9];
721
slotp = reader_table + slot;
723
if (slotp->pcsc.req_fd == -1
724
|| slotp->pcsc.rsp_fd == -1
725
|| slotp->pcsc.pid == (pid_t)(-1) )
727
log_error ("pcsc_get_status: pcsc-wrapper not running\n");
728
return SW_HOST_CARD_IO_ERROR;
731
msgbuf[0] = 0x05; /* RESET command. */
733
msgbuf[1] = (len >> 24);
734
msgbuf[2] = (len >> 16);
735
msgbuf[3] = (len >> 8);
737
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
739
log_error ("error sending PC/SC RESET request: %s\n",
744
/* Read the response. */
745
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
747
log_error ("error receiving PC/SC RESET response: %s\n",
748
i? strerror (errno) : "premature EOF");
751
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
752
if (msgbuf[0] != 0x81 || len < 4)
754
log_error ("invalid response header from PC/SC received\n");
757
len -= 4; /* Already read the error code. */
758
if (len > DIM (slotp->atr))
760
log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
763
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
766
log_error ("PC/SC RESET failed: %s\n", pcsc_error_string (err));
770
/* The open fucntion may return a zero for the ATR length to
771
indicate that no card is present. */
775
if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
777
log_error ("error receiving PC/SC RESET response: %s\n",
778
i? strerror (errno) : "premature EOF");
787
close (slotp->pcsc.req_fd);
788
close (slotp->pcsc.rsp_fd);
789
slotp->pcsc.req_fd = -1;
790
slotp->pcsc.rsp_fd = -1;
791
kill (slotp->pcsc.pid, SIGTERM);
792
slotp->pcsc.pid = (pid_t)(-1);
796
#else /* !NEED_PCSC_WRAPPER */
799
unsigned long nreader, atrlen;
800
unsigned long card_state, card_protocol;
802
if (reader_table[slot].pcsc.card)
804
err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
807
log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
808
pcsc_error_string (err), err);
809
return SW_HOST_CARD_IO_ERROR;
811
reader_table[slot].pcsc.card = 0;
814
err = pcsc_connect (reader_table[slot].pcsc.context,
815
reader_table[slot].rdrname,
816
PCSC_SHARE_EXCLUSIVE,
817
PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
818
&reader_table[slot].pcsc.card,
819
&reader_table[slot].pcsc.protocol);
822
log_error ("pcsc_connect failed: %s (0x%lx)\n",
823
pcsc_error_string (err), err);
824
reader_table[slot].pcsc.card = 0;
825
return SW_HOST_CARD_IO_ERROR;
830
nreader = sizeof reader - 1;
831
err = pcsc_status (reader_table[slot].pcsc.card,
833
&card_state, &card_protocol,
834
reader_table[slot].atr, &atrlen);
837
log_error ("pcsc_status failed: %s (0x%lx)\n",
838
pcsc_error_string (err), err);
839
reader_table[slot].atrlen = 0;
840
return SW_HOST_CARD_IO_ERROR;
842
if (atrlen >= DIM (reader_table[0].atr))
843
log_bug ("ATR returned by pcsc_status is too large\n");
844
reader_table[slot].atrlen = atrlen;
847
#endif /* !NEED_PCSC_WRAPPER */
852
pcsc_get_status (int slot, unsigned int *status)
854
#ifdef NEED_PCSC_WRAPPER
856
reader_table_t slotp;
857
size_t len, full_len;
859
unsigned char msgbuf[9];
860
unsigned char buffer[12];
862
slotp = reader_table + slot;
864
if (slotp->pcsc.req_fd == -1
865
|| slotp->pcsc.rsp_fd == -1
866
|| slotp->pcsc.pid == (pid_t)(-1) )
868
log_error ("pcsc_get_status: pcsc-wrapper not running\n");
869
return SW_HOST_CARD_IO_ERROR;
872
msgbuf[0] = 0x04; /* STATUS command. */
874
msgbuf[1] = (len >> 24);
875
msgbuf[2] = (len >> 16);
876
msgbuf[3] = (len >> 8);
878
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
880
log_error ("error sending PC/SC STATUS request: %s\n",
885
/* Read the response. */
886
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
888
log_error ("error receiving PC/SC STATUS response: %s\n",
889
i? strerror (errno) : "premature EOF");
892
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
893
if (msgbuf[0] != 0x81 || len < 4)
895
log_error ("invalid response header from PC/SC received\n");
898
len -= 4; /* Already read the error code. */
899
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
902
log_error ("pcsc_status failed: %s (0x%lx)\n",
903
pcsc_error_string (err), err);
904
return SW_HOST_CARD_IO_ERROR;
909
n = 8 < len ? 8 : len;
910
if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != 8)
912
log_error ("error receiving PC/SC STATUS response: %s\n",
913
i? strerror (errno) : "premature EOF");
918
/* Newer versions of the wrapper might send more status bytes.
922
unsigned char dummybuf[128];
924
n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
925
if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
927
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
928
i? strerror (errno) : "premature EOF");
934
/* We are lucky: The wrapper already returns the data in the
941
close (slotp->pcsc.req_fd);
942
close (slotp->pcsc.rsp_fd);
943
slotp->pcsc.req_fd = -1;
944
slotp->pcsc.rsp_fd = -1;
945
kill (slotp->pcsc.pid, SIGTERM);
946
slotp->pcsc.pid = (pid_t)(-1);
950
#else /*!NEED_PCSC_WRAPPER*/
953
struct pcsc_readerstate_s rdrstates[1];
955
memset (rdrstates, 0, sizeof *rdrstates);
956
rdrstates[0].reader = reader_table[slot].rdrname;
957
rdrstates[0].current_state = PCSC_STATE_UNAWARE;
958
err = pcsc_get_status_change (reader_table[slot].pcsc.context,
961
if (err == 0x8010000a) /* Timeout. */
965
log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
966
pcsc_error_string (err), err);
967
return SW_HOST_CARD_IO_ERROR;
972
/* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
973
/* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
974
/* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
975
/* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
976
/* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
977
/* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
978
/* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
979
/* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
980
/* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
981
/* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
982
/* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
985
if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
987
if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
989
/* We indicate a useful card if it is not in use by another
990
application. This is because we only use exclusive access
992
if ( (*status & 6) == 6
993
&& !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
997
#endif /*!NEED_PCSC_WRAPPER*/
1001
/* Actually send the APDU of length APDULEN to SLOT and return a
1002
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1003
set to BUFLEN. Returns: CT API error code. */
1005
pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1006
unsigned char *buffer, size_t *buflen)
1008
#ifdef NEED_PCSC_WRAPPER
1010
reader_table_t slotp;
1011
size_t len, full_len;
1013
unsigned char msgbuf[9];
1015
if (!reader_table[slot].atrlen
1016
&& (err = reset_pcsc_reader (slot)))
1020
log_printhex (" PCSC_data:", apdu, apdulen);
1022
slotp = reader_table + slot;
1024
if (slotp->pcsc.req_fd == -1
1025
|| slotp->pcsc.rsp_fd == -1
1026
|| slotp->pcsc.pid == (pid_t)(-1) )
1028
log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1029
return SW_HOST_CARD_IO_ERROR;
1032
msgbuf[0] = 0x03; /* TRANSMIT command. */
1034
msgbuf[1] = (len >> 24);
1035
msgbuf[2] = (len >> 16);
1036
msgbuf[3] = (len >> 8);
1038
if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1039
|| writen (slotp->pcsc.req_fd, apdu, len))
1041
log_error ("error sending PC/SC TRANSMIT request: %s\n",
1043
goto command_failed;
1046
/* Read the response. */
1047
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1049
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1050
i? strerror (errno) : "premature EOF");
1051
goto command_failed;
1053
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1054
if (msgbuf[0] != 0x81 || len < 4)
1056
log_error ("invalid response header from PC/SC received\n");
1057
goto command_failed;
1059
len -= 4; /* Already read the error code. */
1060
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1063
log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1064
pcsc_error_string (err), err);
1065
return SW_HOST_CARD_IO_ERROR;
1070
n = *buflen < len ? *buflen : len;
1071
if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1073
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1074
i? strerror (errno) : "premature EOF");
1075
goto command_failed;
1082
log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1083
err = SW_HOST_INV_VALUE;
1085
/* We need to read any rest of the response, to keep the
1089
unsigned char dummybuf[128];
1091
n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1092
if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1094
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1095
i? strerror (errno) : "premature EOF");
1096
goto command_failed;
1104
close (slotp->pcsc.req_fd);
1105
close (slotp->pcsc.rsp_fd);
1106
slotp->pcsc.req_fd = -1;
1107
slotp->pcsc.rsp_fd = -1;
1108
kill (slotp->pcsc.pid, SIGTERM);
1109
slotp->pcsc.pid = (pid_t)(-1);
1113
#else /*!NEED_PCSC_WRAPPER*/
1116
struct pcsc_io_request_s send_pci;
1117
unsigned long recv_len;
1119
if (!reader_table[slot].atrlen
1120
&& (err = reset_pcsc_reader (slot)))
1124
log_printhex (" PCSC_data:", apdu, apdulen);
1126
if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1127
send_pci.protocol = PCSC_PROTOCOL_T1;
1129
send_pci.protocol = PCSC_PROTOCOL_T0;
1130
send_pci.pci_len = sizeof send_pci;
1132
err = pcsc_transmit (reader_table[slot].pcsc.card,
1133
&send_pci, apdu, apdulen,
1134
NULL, buffer, &recv_len);
1137
log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1138
pcsc_error_string (err), err);
1140
return err? SW_HOST_CARD_IO_ERROR:0;
1141
#endif /*!NEED_PCSC_WRAPPER*/
1146
close_pcsc_reader (int slot)
1148
#ifdef NEED_PCSC_WRAPPER
1150
reader_table_t slotp;
1153
unsigned char msgbuf[9];
1155
slotp = reader_table + slot;
1157
if (slotp->pcsc.req_fd == -1
1158
|| slotp->pcsc.rsp_fd == -1
1159
|| slotp->pcsc.pid == (pid_t)(-1) )
1161
log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1165
msgbuf[0] = 0x02; /* CLOSE command. */
1167
msgbuf[1] = (len >> 24);
1168
msgbuf[2] = (len >> 16);
1169
msgbuf[3] = (len >> 8);
1171
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1173
log_error ("error sending PC/SC CLOSE request: %s\n",
1175
goto command_failed;
1178
/* Read the response. */
1179
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1181
log_error ("error receiving PC/SC CLOSE response: %s\n",
1182
i? strerror (errno) : "premature EOF");
1183
goto command_failed;
1185
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1186
if (msgbuf[0] != 0x81 || len < 4)
1188
log_error ("invalid response header from PC/SC received\n");
1189
goto command_failed;
1191
len -= 4; /* Already read the error code. */
1192
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1194
log_error ("pcsc_close failed: %s (0x%lx)\n",
1195
pcsc_error_string (err), err);
1197
/* We will the wrapper in any case - errors are merely
1201
close (slotp->pcsc.req_fd);
1202
close (slotp->pcsc.rsp_fd);
1203
slotp->pcsc.req_fd = -1;
1204
slotp->pcsc.rsp_fd = -1;
1205
kill (slotp->pcsc.pid, SIGTERM);
1206
slotp->pcsc.pid = (pid_t)(-1);
1210
#else /*!NEED_PCSC_WRAPPER*/
1212
pcsc_release_context (reader_table[slot].pcsc.context);
1213
xfree (reader_table[slot].rdrname);
1214
reader_table[slot].rdrname = NULL;
1215
reader_table[slot].used = 0;
1217
#endif /*!NEED_PCSC_WRAPPER*/
1221
open_pcsc_reader (const char *portstr)
1223
#ifdef NEED_PCSC_WRAPPER
1224
/* Open the PC/SC reader using the pcsc_wrapper program. This is
1225
needed to cope with different thread models and other peculiarities
1228
reader_table_t slotp;
1229
int fd, rp[2], wp[2];
1233
unsigned char msgbuf[9];
1236
slot = new_reader_slot ();
1239
slotp = reader_table + slot;
1241
/* Fire up the pcsc wrapper. We don't use any fork/exec code from
1242
the common directy but implement it direclty so that this file
1243
may still be source copied. */
1245
if (pipe (rp) == -1)
1247
log_error ("error creating a pipe: %s\n", strerror (errno));
1251
if (pipe (wp) == -1)
1253
log_error ("error creating a pipe: %s\n", strerror (errno));
1263
log_error ("error forking process: %s\n", strerror (errno));
1271
slotp->pcsc.pid = pid;
1283
_exit (0); /* Immediate exit this parent, so that the child
1284
gets cleaned up by the init process. */
1286
/* Connect our pipes. */
1287
if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1288
log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1289
if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1290
log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1292
/* Send stderr to the bit bucket. */
1293
fd = open ("/dev/null", O_WRONLY);
1295
log_fatal ("can't open `/dev/null': %s", strerror (errno));
1296
if (fd != 2 && dup2 (fd, 2) == -1)
1297
log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1299
/* Close all other files. */
1300
n = sysconf (_SC_OPEN_MAX);
1303
for (i=3; i < n; i++)
1307
execl (GNUPG_LIBDIR "/pcsc-wrapper",
1310
"1", /* API version */
1311
opt.pcsc_driver, /* Name of the PC/SC library. */
1321
slotp->pcsc.req_fd = wp[1];
1322
slotp->pcsc.rsp_fd = rp[0];
1324
/* Wait for the intermediate child to terminate. */
1326
#define WAIT pth_waitpid
1328
#define WAIT waitpid
1330
while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1334
/* Now send the open request. */
1335
msgbuf[0] = 0x01; /* OPEN command. */
1336
len = portstr? strlen (portstr):0;
1337
msgbuf[1] = (len >> 24);
1338
msgbuf[2] = (len >> 16);
1339
msgbuf[3] = (len >> 8);
1341
if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1342
|| (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1344
log_error ("error sending PC/SC OPEN request: %s\n",
1346
goto command_failed;
1348
/* Read the response. */
1349
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1351
log_error ("error receiving PC/SC OPEN response: %s\n",
1352
i? strerror (errno) : "premature EOF");
1353
goto command_failed;
1355
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1356
if (msgbuf[0] != 0x81 || len < 4)
1358
log_error ("invalid response header from PC/SC received\n");
1359
goto command_failed;
1361
len -= 4; /* Already read the error code. */
1362
if (len > DIM (slotp->atr))
1364
log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
1365
goto command_failed;
1367
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1370
log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1371
goto command_failed;
1374
slotp->last_status = 0;
1376
/* The open fucntion may return a zero for the ATR length to
1377
indicate that no card is present. */
1381
if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1383
log_error ("error receiving PC/SC OPEN response: %s\n",
1384
i? strerror (errno) : "premature EOF");
1385
goto command_failed;
1387
/* If we got to here we know that a card is present
1388
and usable. Thus remember this. */
1389
slotp->last_status = (1|2|4| 0x8000);
1391
slotp->atrlen = len;
1393
reader_table[slot].close_reader = close_pcsc_reader;
1394
reader_table[slot].reset_reader = reset_pcsc_reader;
1395
reader_table[slot].get_status_reader = pcsc_get_status;
1396
reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1397
reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1399
dump_reader_status (slot);
1403
close (slotp->pcsc.req_fd);
1404
close (slotp->pcsc.rsp_fd);
1405
slotp->pcsc.req_fd = -1;
1406
slotp->pcsc.rsp_fd = -1;
1407
kill (slotp->pcsc.pid, SIGTERM);
1408
slotp->pcsc.pid = (pid_t)(-1);
1411
#else /*!NEED_PCSC_WRAPPER */
1415
unsigned long nreader, listlen, atrlen;
1417
unsigned long card_state, card_protocol;
1419
slot = new_reader_slot ();
1423
err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1424
&reader_table[slot].pcsc.context);
1427
log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1428
pcsc_error_string (err), err);
1429
reader_table[slot].used = 0;
1433
err = pcsc_list_readers (reader_table[slot].pcsc.context,
1434
NULL, NULL, &nreader);
1437
list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1440
log_error ("error allocating memory for reader list\n");
1441
pcsc_release_context (reader_table[slot].pcsc.context);
1442
reader_table[slot].used = 0;
1445
err = pcsc_list_readers (reader_table[slot].pcsc.context,
1446
NULL, list, &nreader);
1450
log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1451
pcsc_error_string (err), err);
1452
pcsc_release_context (reader_table[slot].pcsc.context);
1453
reader_table[slot].used = 0;
1465
log_info ("detected reader `%s'\n", p);
1466
if (nreader < (strlen (p)+1))
1468
log_error ("invalid response from pcsc_list_readers\n");
1471
nreader -= strlen (p)+1;
1472
p += strlen (p) + 1;
1475
reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1476
if (!reader_table[slot].rdrname)
1478
log_error ("error allocating memory for reader name\n");
1479
pcsc_release_context (reader_table[slot].pcsc.context);
1480
reader_table[slot].used = 0;
1483
strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1487
err = pcsc_connect (reader_table[slot].pcsc.context,
1488
reader_table[slot].rdrname,
1489
PCSC_SHARE_EXCLUSIVE,
1490
PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1491
&reader_table[slot].pcsc.card,
1492
&reader_table[slot].pcsc.protocol);
1493
if (err == 0x8010000c) /* No smartcard. */
1494
reader_table[slot].pcsc.card = 0;
1497
log_error ("pcsc_connect failed: %s (0x%lx)\n",
1498
pcsc_error_string (err), err);
1500
pcsc_release_context (reader_table[slot].pcsc.context);
1501
xfree (reader_table[slot].rdrname);
1502
reader_table[slot].rdrname = NULL;
1503
reader_table[slot].used = 0;
1507
reader_table[slot].atrlen = 0;
1508
reader_table[slot].last_status = 0;
1512
unsigned long readerlen;
1515
readerlen = sizeof reader -1 ;
1516
err = pcsc_status (reader_table[slot].pcsc.card,
1518
&card_state, &card_protocol,
1519
reader_table[slot].atr, &atrlen);
1521
log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1522
pcsc_error_string (err), err, readerlen);
1525
if (atrlen >= DIM (reader_table[0].atr))
1526
log_bug ("ATR returned by pcsc_status is too large\n");
1527
reader_table[slot].atrlen = atrlen;
1528
/* If we got to here we know that a card is present
1529
and usable. Thus remember this. */
1530
reader_table[slot].last_status = (1|2|4| 0x8000);
1534
reader_table[slot].close_reader = close_pcsc_reader;
1535
reader_table[slot].reset_reader = reset_pcsc_reader;
1536
reader_table[slot].get_status_reader = pcsc_get_status;
1537
reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1538
reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1540
/* log_debug ("state from pcsc_status: 0x%lx\n", card_state); */
1541
/* log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
1543
dump_reader_status (slot);
1545
#endif /*!NEED_PCSC_WRAPPER */
1553
Internal CCID driver interface.
1558
dump_ccid_reader_status (int slot)
1560
log_info ("reader slot %d: using ccid driver\n", slot);
1564
close_ccid_reader (int slot)
1566
ccid_close_reader (reader_table[slot].ccid.handle);
1567
reader_table[slot].used = 0;
1573
shutdown_ccid_reader (int slot)
1575
ccid_shutdown_reader (reader_table[slot].ccid.handle);
1581
reset_ccid_reader (int slot)
1584
reader_table_t slotp = reader_table + slot;
1585
unsigned char atr[33];
1588
err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1591
/* If the reset was successful, update the ATR. */
1592
assert (sizeof slotp->atr >= sizeof atr);
1593
slotp->atrlen = atrlen;
1594
memcpy (slotp->atr, atr, atrlen);
1595
dump_reader_status (slot);
1601
get_status_ccid (int slot, unsigned int *status)
1606
rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1621
/* Actually send the APDU of length APDULEN to SLOT and return a
1622
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1623
set to BUFLEN. Returns: Internal CCID driver error code. */
1625
send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1626
unsigned char *buffer, size_t *buflen)
1631
/* If we don't have an ATR, we need to reset the reader first. */
1632
if (!reader_table[slot].atrlen
1633
&& (err = reset_ccid_reader (slot)))
1637
log_printhex (" APDU_data:", apdu, apdulen);
1639
maxbuflen = *buflen;
1640
err = ccid_transceive (reader_table[slot].ccid.handle,
1642
buffer, maxbuflen, buflen);
1644
log_error ("ccid_transceive failed: (0x%lx)\n",
1650
/* Open the reader and try to read an ATR. */
1652
open_ccid_reader (const char *portstr)
1656
reader_table_t slotp;
1658
slot = new_reader_slot ();
1661
slotp = reader_table + slot;
1663
err = ccid_open_reader (&slotp->ccid.handle, portstr);
1670
err = ccid_get_atr (slotp->ccid.handle,
1671
slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1679
/* If we got to here we know that a card is present
1680
and usable. Thus remember this. */
1681
reader_table[slot].last_status = (1|2|4| 0x8000);
1684
reader_table[slot].close_reader = close_ccid_reader;
1685
reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1686
reader_table[slot].reset_reader = reset_ccid_reader;
1687
reader_table[slot].get_status_reader = get_status_ccid;
1688
reader_table[slot].send_apdu_reader = send_apdu_ccid;
1689
reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1691
dump_reader_status (slot);
1697
#endif /* HAVE_LIBUSB */
1705
This uses the OpenSC primitives to send APDUs. We need this
1706
because we can't mix OpenSC and native (i.e. ctAPI or PC/SC)
1707
access to a card for resource conflict reasons.
1712
close_osc_reader (int slot)
1714
/* FIXME: Implement. */
1715
reader_table[slot].used = 0;
1720
reset_osc_reader (int slot)
1722
return SW_HOST_NOT_SUPPORTED;
1727
osc_get_status (int slot, unsigned int *status)
1729
return SW_HOST_NOT_SUPPORTED;
1733
/* Actually send the APDU of length APDULEN to SLOT and return a
1734
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1735
set to BUFLEN. Returns: OpenSC error code. */
1737
osc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1738
unsigned char *buffer, size_t *buflen)
1742
unsigned char data[SC_MAX_APDU_BUFFER_SIZE];
1743
unsigned char result[SC_MAX_APDU_BUFFER_SIZE];
1746
log_printhex (" APDU_data:", apdu, apdulen);
1750
log_error ("osc_send_apdu: APDU is too short\n");
1751
return SW_HOST_INV_VALUE;
1754
memset(&a, 0, sizeof a);
1762
a.cse = SC_APDU_CASE_1;
1763
else if (apdulen == 1)
1765
a.le = *apdu? *apdu : 256;
1767
a.cse = SC_APDU_CASE_2_SHORT;
1771
a.lc = *apdu++; apdulen--;
1774
log_error ("osc_send_apdu: APDU shorter than specified in Lc\n");
1775
return SW_HOST_INV_VALUE;
1778
memcpy(data, apdu, a.lc);
1779
apdu += a.lc; apdulen -= a.lc;
1785
a.cse = SC_APDU_CASE_3_SHORT;
1788
a.le = *apdu? *apdu : 256;
1792
log_error ("osc_send_apdu: APDU larger than specified\n");
1793
return SW_HOST_INV_VALUE;
1795
a.cse = SC_APDU_CASE_4_SHORT;
1800
a.resplen = DIM(result);
1802
err = sc_transmit_apdu (reader_table[slot].osc.scard, &a);
1805
log_error ("sc_apdu_transmit failed: %s\n", sc_strerror (err));
1806
return SW_HOST_CARD_IO_ERROR;
1809
if (*buflen < 2 || a.resplen > *buflen - 2)
1811
log_error ("osc_send_apdu: provided buffer too short to store result\n");
1812
return SW_HOST_INV_VALUE;
1814
memcpy (buffer, a.resp, a.resplen);
1815
buffer[a.resplen] = a.sw1;
1816
buffer[a.resplen+1] = a.sw2;
1817
*buflen = a.resplen + 2;
1822
open_osc_reader (int portno)
1826
reader_table_t slotp;
1828
slot = new_reader_slot ();
1831
slotp = reader_table + slot;
1833
err = sc_establish_context (&slotp->osc.ctx, "scdaemon");
1836
log_error ("failed to establish SC context: %s\n", sc_strerror (err));
1840
if (portno < 0 || portno >= slotp->osc.ctx->reader_count)
1842
log_error ("no card reader available\n");
1843
sc_release_context (slotp->osc.ctx);
1848
/* Redirect to our logging facility. */
1849
slotp->osc.ctx->error_file = log_get_stream ();
1850
slotp->osc.ctx->debug = opt.debug_sc;
1851
slotp->osc.ctx->debug_file = log_get_stream ();
1853
if (sc_detect_card_presence (slotp->osc.ctx->reader[portno], 0) != 1)
1855
log_error ("no card present\n");
1856
sc_release_context (slotp->osc.ctx);
1861
/* We want the standard ISO driver. */
1862
/*FIXME: OpenSC does not like "iso7816", so we use EMV for now. */
1863
err = sc_set_card_driver(slotp->osc.ctx, "emv");
1866
log_error ("failed to select the iso7816 driver: %s\n",
1868
sc_release_context (slotp->osc.ctx);
1873
/* Now connect the card and hope that OpenSC won't try to be too
1875
err = sc_connect_card (slotp->osc.ctx->reader[portno], 0,
1879
log_error ("failed to connect card in reader %d: %s\n",
1880
portno, sc_strerror (err));
1881
sc_release_context (slotp->osc.ctx);
1886
log_info ("connected to card in opensc reader %d using driver `%s'\n",
1887
portno, slotp->osc.scard->driver->name);
1889
err = sc_lock (slotp->osc.scard);
1892
log_error ("can't lock card in reader %d: %s\n",
1893
portno, sc_strerror (err));
1894
sc_disconnect_card (slotp->osc.scard, 0);
1895
sc_release_context (slotp->osc.ctx);
1900
if (slotp->osc.scard->atr_len >= DIM (slotp->atr))
1901
log_bug ("ATR returned by opensc is too large\n");
1902
slotp->atrlen = slotp->osc.scard->atr_len;
1903
memcpy (slotp->atr, slotp->osc.scard->atr, slotp->atrlen);
1905
reader_table[slot].close_reader = close_osc_reader;
1906
reader_table[slot].reset_reader = reset_osc_reader;
1907
reader_table[slot].get_status_reader = osc_get_status;
1908
reader_table[slot].send_apdu_reader = osc_send_apdu;
1909
reader_table[slot].dump_status_reader = NULL;
1911
dump_reader_status (slot);
1915
#endif /* HAVE_OPENSC */
1919
#ifdef USE_G10CODE_RAPDU
1921
The Remote APDU Interface.
1923
This uses the Remote APDU protocol to contact a reader.
1925
The port number is actually an index into the list of ports as
1926
returned via the protocol.
1931
rapdu_status_to_sw (int status)
1937
case RAPDU_STATUS_SUCCESS: rc = 0; break;
1939
case RAPDU_STATUS_INVCMD:
1940
case RAPDU_STATUS_INVPROT:
1941
case RAPDU_STATUS_INVSEQ:
1942
case RAPDU_STATUS_INVCOOKIE:
1943
case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1945
case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1946
case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1947
case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1948
case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1949
case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1950
case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1952
default: rc = SW_HOST_GENERAL_ERROR; break;
1961
close_rapdu_reader (int slot)
1963
rapdu_release (reader_table[slot].rapdu.handle);
1964
reader_table[slot].used = 0;
1970
reset_rapdu_reader (int slot)
1973
reader_table_t slotp;
1974
rapdu_msg_t msg = NULL;
1976
slotp = reader_table + slot;
1978
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1981
log_error ("sending rapdu command RESET failed: %s\n",
1982
err < 0 ? strerror (errno): rapdu_strerror (err));
1983
rapdu_msg_release (msg);
1984
return rapdu_status_to_sw (err);
1986
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1989
log_error ("receiving rapdu message failed: %s\n",
1990
err < 0 ? strerror (errno): rapdu_strerror (err));
1991
rapdu_msg_release (msg);
1992
return rapdu_status_to_sw (err);
1994
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1996
int sw = rapdu_status_to_sw (msg->cmd);
1997
log_error ("rapdu command RESET failed: %s\n",
1998
rapdu_strerror (msg->cmd));
1999
rapdu_msg_release (msg);
2002
if (msg->datalen >= DIM (slotp->atr))
2004
log_error ("ATR returned by the RAPDU layer is too large\n");
2005
rapdu_msg_release (msg);
2006
return SW_HOST_INV_VALUE;
2008
slotp->atrlen = msg->datalen;
2009
memcpy (slotp->atr, msg->data, msg->datalen);
2011
rapdu_msg_release (msg);
2017
my_rapdu_get_status (int slot, unsigned int *status)
2020
reader_table_t slotp;
2021
rapdu_msg_t msg = NULL;
2024
slotp = reader_table + slot;
2026
oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2027
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2028
rapdu_set_reader (slotp->rapdu.handle, oldslot);
2031
log_error ("sending rapdu command GET_STATUS failed: %s\n",
2032
err < 0 ? strerror (errno): rapdu_strerror (err));
2033
return rapdu_status_to_sw (err);
2035
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2038
log_error ("receiving rapdu message failed: %s\n",
2039
err < 0 ? strerror (errno): rapdu_strerror (err));
2040
rapdu_msg_release (msg);
2041
return rapdu_status_to_sw (err);
2043
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2045
int sw = rapdu_status_to_sw (msg->cmd);
2046
log_error ("rapdu command GET_STATUS failed: %s\n",
2047
rapdu_strerror (msg->cmd));
2048
rapdu_msg_release (msg);
2051
*status = msg->data[0];
2053
rapdu_msg_release (msg);
2058
/* Actually send the APDU of length APDULEN to SLOT and return a
2059
maximum of *BUFLEN data in BUFFER, the actual returned size will be
2060
set to BUFLEN. Returns: OpenSC error code. */
2062
my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2063
unsigned char *buffer, size_t *buflen)
2066
reader_table_t slotp;
2067
rapdu_msg_t msg = NULL;
2068
size_t maxlen = *buflen;
2070
slotp = reader_table + slot;
2074
log_printhex (" APDU_data:", apdu, apdulen);
2078
log_error ("rapdu_send_apdu: APDU is too short\n");
2079
return SW_HOST_INV_VALUE;
2082
err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2085
log_error ("sending rapdu command APDU failed: %s\n",
2086
err < 0 ? strerror (errno): rapdu_strerror (err));
2087
rapdu_msg_release (msg);
2088
return rapdu_status_to_sw (err);
2090
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2093
log_error ("receiving rapdu message failed: %s\n",
2094
err < 0 ? strerror (errno): rapdu_strerror (err));
2095
rapdu_msg_release (msg);
2096
return rapdu_status_to_sw (err);
2098
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2100
int sw = rapdu_status_to_sw (msg->cmd);
2101
log_error ("rapdu command APDU failed: %s\n",
2102
rapdu_strerror (msg->cmd));
2103
rapdu_msg_release (msg);
2107
if (msg->datalen > maxlen)
2109
log_error ("rapdu response apdu too large\n");
2110
rapdu_msg_release (msg);
2111
return SW_HOST_INV_VALUE;
2114
*buflen = msg->datalen;
2115
memcpy (buffer, msg->data, msg->datalen);
2117
rapdu_msg_release (msg);
2122
open_rapdu_reader (int portno,
2123
const unsigned char *cookie, size_t length,
2124
int (*readfnc) (void *opaque,
2125
void *buffer, size_t size),
2126
void *readfnc_value,
2127
int (*writefnc) (void *opaque,
2128
const void *buffer, size_t size),
2129
void *writefnc_value,
2130
void (*closefnc) (void *opaque),
2131
void *closefnc_value)
2135
reader_table_t slotp;
2136
rapdu_msg_t msg = NULL;
2138
slot = new_reader_slot ();
2141
slotp = reader_table + slot;
2143
slotp->rapdu.handle = rapdu_new ();
2144
if (!slotp->rapdu.handle)
2151
rapdu_set_iofunc (slotp->rapdu.handle,
2152
readfnc, readfnc_value,
2153
writefnc, writefnc_value,
2154
closefnc, closefnc_value);
2155
rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2157
/* First try to get the current ATR, but if the card is inactive
2158
issue a reset instead. */
2159
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2160
if (err == RAPDU_STATUS_NEEDRESET)
2161
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2164
log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2165
err < 0 ? strerror (errno): rapdu_strerror (err));
2168
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2171
log_info ("receiving rapdu message failed: %s\n",
2172
err < 0 ? strerror (errno): rapdu_strerror (err));
2175
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2177
log_info ("rapdu command GET ATR failed: %s\n",
2178
rapdu_strerror (msg->cmd));
2181
if (msg->datalen >= DIM (slotp->atr))
2183
log_error ("ATR returned by the RAPDU layer is too large\n");
2186
slotp->atrlen = msg->datalen;
2187
memcpy (slotp->atr, msg->data, msg->datalen);
2189
reader_table[slot].close_reader = close_rapdu_reader;
2190
reader_table[slot].reset_reader = reset_rapdu_reader;
2191
reader_table[slot].get_status_reader = my_rapdu_get_status;
2192
reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2193
reader_table[slot].dump_status_reader = NULL;
2195
dump_reader_status (slot);
2196
rapdu_msg_release (msg);
2200
rapdu_msg_release (msg);
2201
rapdu_release (slotp->rapdu.handle);
2206
#endif /*USE_G10CODE_RAPDU*/
2216
lock_slot (int slot)
2219
if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2221
log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2222
return SW_HOST_LOCKING_FAILED;
2224
#endif /*USE_GNU_PTH*/
2229
trylock_slot (int slot)
2232
if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2235
return SW_HOST_BUSY;
2236
log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2237
return SW_HOST_LOCKING_FAILED;
2239
#endif /*USE_GNU_PTH*/
2244
unlock_slot (int slot)
2247
if (!pth_mutex_release (&reader_table[slot].lock))
2248
log_error ("failed to release apdu lock: %s\n", strerror (errno));
2249
#endif /*USE_GNU_PTH*/
2253
/* Open the reader and return an internal slot number or -1 on
2254
error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2255
the first USB reader. For PC/SC the first listed reader). If
2256
OpenSC support is compiled in, we first try to use OpenSC. */
2258
apdu_open_reader (const char *portstr)
2260
static int pcsc_api_loaded, ct_api_loaded;
2263
if (!opt.disable_ccid)
2268
slot = open_ccid_reader (portstr);
2270
return slot; /* got one */
2272
/* If a CCID reader specification has been given, the user does
2273
not want a fallback to other drivers. */
2275
for (s=portstr, i=0; *s; s++)
2276
if (*s == ':' && (++i == 3))
2280
#endif /* HAVE_LIBUSB */
2283
if (!opt.disable_opensc)
2285
int port = portstr? atoi (portstr) : 0;
2287
return open_osc_reader (port);
2289
#endif /* HAVE_OPENSC */
2292
if (opt.ctapi_driver && *opt.ctapi_driver)
2294
int port = portstr? atoi (portstr) : 32768;
2300
handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2303
log_error ("apdu_open_reader: failed to open driver: %s\n",
2307
CT_init = dlsym (handle, "CT_init");
2308
CT_data = dlsym (handle, "CT_data");
2309
CT_close = dlsym (handle, "CT_close");
2310
if (!CT_init || !CT_data || !CT_close)
2312
log_error ("apdu_open_reader: invalid CT-API driver\n");
2318
return open_ct_reader (port);
2322
/* No ctAPI configured, so lets try the PC/SC API */
2323
if (!pcsc_api_loaded)
2325
#ifndef NEED_PCSC_WRAPPER
2328
handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2331
log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2332
opt.pcsc_driver, dlerror ());
2336
pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2337
pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2338
pcsc_list_readers = dlsym (handle, "SCardListReaders");
2340
if (!pcsc_list_readers)
2341
pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2343
pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2345
if (!pcsc_get_status_change)
2346
pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2348
pcsc_connect = dlsym (handle, "SCardConnect");
2351
pcsc_connect = dlsym (handle, "SCardConnectA");
2353
pcsc_reconnect = dlsym (handle, "SCardReconnect");
2355
if (!pcsc_reconnect)
2356
pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2358
pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2359
pcsc_status = dlsym (handle, "SCardStatus");
2362
pcsc_status = dlsym (handle, "SCardStatusA");
2364
pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2365
pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2366
pcsc_transmit = dlsym (handle, "SCardTransmit");
2367
pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2369
if (!pcsc_establish_context
2370
|| !pcsc_release_context
2371
|| !pcsc_list_readers
2372
|| !pcsc_get_status_change
2377
|| !pcsc_begin_transaction
2378
|| !pcsc_end_transaction
2380
/* || !pcsc_set_timeout */)
2382
/* Note that set_timeout is currently not used and also not
2383
available under Windows. */
2384
log_error ("apdu_open_reader: invalid PC/SC driver "
2385
"(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2386
!!pcsc_establish_context,
2387
!!pcsc_release_context,
2388
!!pcsc_list_readers,
2389
!!pcsc_get_status_change,
2394
!!pcsc_begin_transaction,
2395
!!pcsc_end_transaction,
2397
!!pcsc_set_timeout );
2401
#endif /*!NEED_PCSC_WRAPPER*/
2402
pcsc_api_loaded = 1;
2405
return open_pcsc_reader (portstr);
2409
/* Open an remote reader and return an internal slot number or -1 on
2410
error. This function is an alternative to apdu_open_reader and used
2411
with remote readers only. Note that the supplied CLOSEFNC will
2412
only be called once and the slot will not be valid afther this.
2414
If PORTSTR is NULL we default to the first availabe port.
2417
apdu_open_remote_reader (const char *portstr,
2418
const unsigned char *cookie, size_t length,
2419
int (*readfnc) (void *opaque,
2420
void *buffer, size_t size),
2421
void *readfnc_value,
2422
int (*writefnc) (void *opaque,
2423
const void *buffer, size_t size),
2424
void *writefnc_value,
2425
void (*closefnc) (void *opaque),
2426
void *closefnc_value)
2428
#ifdef USE_G10CODE_RAPDU
2429
return open_rapdu_reader (portstr? atoi (portstr) : 0,
2431
readfnc, readfnc_value,
2432
writefnc, writefnc_value,
2433
closefnc, closefnc_value);
2446
apdu_close_reader (int slot)
2448
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2449
return SW_HOST_NO_DRIVER;
2450
if (reader_table[slot].close_reader)
2451
return reader_table[slot].close_reader (slot);
2452
return SW_HOST_NOT_SUPPORTED;
2455
/* Shutdown a reader; that is basically the same as a close but keeps
2456
the handle ready for later use. A apdu_reset_header should be used
2457
to get it active again. */
2459
apdu_shutdown_reader (int slot)
2461
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2462
return SW_HOST_NO_DRIVER;
2463
if (reader_table[slot].shutdown_reader)
2464
return reader_table[slot].shutdown_reader (slot);
2465
return SW_HOST_NOT_SUPPORTED;
2468
/* Enumerate all readers and return information on whether this reader
2469
is in use. The caller should start with SLOT set to 0 and
2470
increment it with each call until an error is returned. */
2472
apdu_enum_reader (int slot, int *used)
2474
if (slot < 0 || slot >= MAX_READER)
2475
return SW_HOST_NO_DRIVER;
2476
*used = reader_table[slot].used;
2480
/* Do a reset for the card in reader at SLOT. */
2482
apdu_reset (int slot)
2486
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2487
return SW_HOST_NO_DRIVER;
2489
if ((sw = lock_slot (slot)))
2492
reader_table[slot].last_status = 0;
2493
if (reader_table[slot].reset_reader)
2494
sw = reader_table[slot].reset_reader (slot);
2498
/* If we got to here we know that a card is present
2499
and usable. Thus remember this. */
2500
reader_table[slot].last_status = (1|2|4| 0x8000);
2508
/* Activate a card if it has not yet been done. This is a kind of
2509
reset-if-required. It is useful to test for presence of a card
2510
before issuing a bunch of apdu commands. It does not wait on a
2513
apdu_activate (int slot)
2518
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2519
return SW_HOST_NO_DRIVER;
2521
if ((sw = trylock_slot (slot)))
2524
if (reader_table[slot].get_status_reader)
2525
sw = reader_table[slot].get_status_reader (slot, &s);
2529
if (!(s & 2)) /* Card not present. */
2530
sw = SW_HOST_NO_CARD;
2531
else if ( ((s & 2) && !(s & 4))
2532
|| !reader_table[slot].atrlen )
2534
/* We don't have an ATR or a card is present though inactive:
2536
if (reader_table[slot].reset_reader)
2538
reader_table[slot].last_status = 0;
2539
sw = reader_table[slot].reset_reader (slot);
2542
/* If we got to here we know that a card is present
2543
and usable. Thus remember this. */
2544
reader_table[slot].last_status = (1|2|4| 0x8000);
2557
apdu_get_atr (int slot, size_t *atrlen)
2561
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2564
buf = xtrymalloc (reader_table[slot].atrlen);
2567
memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2568
*atrlen = reader_table[slot].atrlen;
2574
/* Retrieve the status for SLOT. The function does only wait for the
2575
card to become available if HANG is set to true. On success the
2576
bits in STATUS will be set to
2578
bit 0 = card present and usable
2579
bit 1 = card present
2581
bit 3 = card access locked [not yet implemented]
2583
For must application, testing bit 0 is sufficient.
2585
CHANGED will receive the value of the counter tracking the number
2586
of card insertions. This value may be used to detect a card
2590
apdu_get_status (int slot, int hang,
2591
unsigned int *status, unsigned int *changed)
2596
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2597
return SW_HOST_NO_DRIVER;
2599
if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2602
if (reader_table[slot].get_status_reader)
2603
sw = reader_table[slot].get_status_reader (slot, &s);
2609
reader_table[slot].last_status = 0;
2613
/* Keep track of changes. We use one extra bit to test whether we
2614
have checked the status at least once. */
2615
if ( s != (reader_table[slot].last_status & 0x07ff)
2616
|| !reader_table[slot].last_status )
2618
reader_table[slot].change_counter++;
2619
/* Make sure that the ATR is invalid so that a reset will be by
2621
reader_table[slot].atrlen = 0;
2623
reader_table[slot].last_status = (s | 0x8000);
2628
*changed = reader_table[slot].change_counter;
2633
/* Dispatcher for the actual send_apdu function. Note, that this
2634
function should be called in locked state. */
2636
send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2637
unsigned char *buffer, size_t *buflen)
2639
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2640
return SW_HOST_NO_DRIVER;
2642
if (reader_table[slot].send_apdu_reader)
2643
return reader_table[slot].send_apdu_reader (slot,
2647
return SW_HOST_NOT_SUPPORTED;
2650
/* Send an APDU to the card in SLOT. The APDU is created from all
2651
given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2652
for LC won't sent this field and the data field; in this case DATA
2653
must also be passed as NULL. The return value is the status word
2654
or -1 for an invalid SLOT or other non card related error. If
2655
RETBUF is not NULL, it will receive an allocated buffer with the
2656
returned data. The length of that data will be put into
2657
*RETBUFLEN. The caller is reponsible for releasing the buffer even
2658
in case of errors. */
2660
apdu_send_le(int slot, int class, int ins, int p0, int p1,
2661
int lc, const char *data, int le,
2662
unsigned char **retbuf, size_t *retbuflen)
2664
#define RESULTLEN 256
2665
unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2668
unsigned char apdu[5+256+1];
2671
long rc; /* we need a long here due to PC/SC. */
2673
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2674
return SW_HOST_NO_DRIVER;
2677
log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
2678
class, ins, p0, p1, lc, le);
2680
if (lc != -1 && (lc > 255 || lc < 0))
2681
return SW_WRONG_LENGTH;
2682
if (le != -1 && (le > 256 || le < 1))
2683
return SW_WRONG_LENGTH;
2684
if ((!data && lc != -1) || (data && lc == -1))
2685
return SW_HOST_INV_VALUE;
2687
if ((sw = lock_slot (slot)))
2691
apdu[apdulen++] = class;
2692
apdu[apdulen++] = ins;
2693
apdu[apdulen++] = p0;
2694
apdu[apdulen++] = p1;
2697
apdu[apdulen++] = lc;
2698
memcpy (apdu+apdulen, data, lc);
2702
apdu[apdulen++] = le; /* Truncation is okay becuase 0 means 256. */
2703
assert (sizeof (apdu) >= apdulen);
2704
/* As safeguard don't pass any garbage from the stack to the driver. */
2705
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2706
resultlen = RESULTLEN;
2707
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2708
if (rc || resultlen < 2)
2710
log_error ("apdu_send_simple(%d) failed: %s\n",
2711
slot, apdu_strerror (rc));
2713
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2715
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2716
/* store away the returned data but strip the statusword. */
2720
log_debug (" response: sw=%04X datalen=%u\n",
2721
sw, (unsigned int)resultlen);
2722
if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2723
log_printhex (" dump: ", result, resultlen);
2726
if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2730
*retbuf = xtrymalloc (resultlen? resultlen : 1);
2734
return SW_HOST_OUT_OF_CORE;
2736
*retbuflen = resultlen;
2737
memcpy (*retbuf, result, resultlen);
2740
else if ((sw & 0xff00) == SW_MORE_DATA)
2742
unsigned char *p = NULL, *tmp;
2743
size_t bufsize = 4096;
2745
/* It is likely that we need to return much more data, so we
2746
start off with a large buffer. */
2749
*retbuf = p = xtrymalloc (bufsize);
2753
return SW_HOST_OUT_OF_CORE;
2755
assert (resultlen < bufsize);
2756
memcpy (p, result, resultlen);
2762
int len = (sw & 0x00ff);
2765
log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2768
apdu[apdulen++] = class;
2769
apdu[apdulen++] = 0xC0;
2770
apdu[apdulen++] = 0;
2771
apdu[apdulen++] = 0;
2772
apdu[apdulen++] = len;
2773
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2774
resultlen = RESULTLEN;
2775
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2776
if (rc || resultlen < 2)
2778
log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2779
slot, apdu_strerror (rc));
2781
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2783
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2787
log_debug (" more: sw=%04X datalen=%u\n",
2788
sw, (unsigned int)resultlen);
2789
if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2790
log_printhex (" dump: ", result, resultlen);
2793
if ((sw & 0xff00) == SW_MORE_DATA
2795
|| sw == SW_EOF_REACHED )
2797
if (retbuf && resultlen)
2799
if (p - *retbuf + resultlen > bufsize)
2801
bufsize += resultlen > 4096? resultlen: 4096;
2802
tmp = xtryrealloc (*retbuf, bufsize);
2806
return SW_HOST_OUT_OF_CORE;
2808
p = tmp + (p - *retbuf);
2811
memcpy (p, result, resultlen);
2816
log_info ("apdu_send_simple(%d) "
2817
"got unexpected status %04X from get response\n",
2820
while ((sw & 0xff00) == SW_MORE_DATA);
2824
*retbuflen = p - *retbuf;
2825
tmp = xtryrealloc (*retbuf, *retbuflen);
2833
if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2834
log_printhex (" dump: ", *retbuf, *retbuflen);
2840
/* Send an APDU to the card in SLOT. The APDU is created from all
2841
given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2842
LC won't sent this field and the data field; in this case DATA must
2843
also be passed as NULL. The return value is the status word or -1
2844
for an invalid SLOT or other non card related error. If RETBUF is
2845
not NULL, it will receive an allocated buffer with the returned
2846
data. The length of that data will be put into *RETBUFLEN. The
2847
caller is reponsible for releasing the buffer even in case of
2850
apdu_send (int slot, int class, int ins, int p0, int p1,
2851
int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2853
return apdu_send_le (slot, class, ins, p0, p1, lc, data, 256,
2857
/* Send an APDU to the card in SLOT. The APDU is created from all
2858
given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2859
LC won't sent this field and the data field; in this case DATA must
2860
also be passed as NULL. The return value is the status word or -1
2861
for an invalid SLOT or other non card related error. No data will be
2864
apdu_send_simple (int slot, int class, int ins, int p0, int p1,
2865
int lc, const char *data)
2867
return apdu_send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL);
2871
/* This is a more generic version of the apdu sending routine. It
2872
takes an already formatted APDU in APDUDATA or length APDUDATALEN
2873
and returns the with the APDU including the status word. With
2874
HANDLE_MORE set to true this function will handle the MORE DATA
2875
status and return all APDUs concatenated with one status word at
2876
the end. The function does not return a regular status word but 0
2877
on success. If the slot is locked, the fucntion returns
2880
apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
2882
unsigned char **retbuf, size_t *retbuflen)
2884
#define RESULTLEN 256
2885
unsigned char apdu[5+256+1];
2887
unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2891
long rc; /* we need a long here due to PC/SC. */
2894
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2895
return SW_HOST_NO_DRIVER;
2897
if ((sw = trylock_slot (slot)))
2900
/* We simply trucntate a too long APDU. */
2901
if (apdudatalen > sizeof apdu)
2902
apdudatalen = sizeof apdu;
2903
apdulen = apdudatalen;
2904
memcpy (apdu, apdudata, apdudatalen);
2905
class = apdulen? *apdu : 0;
2908
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2909
if (rc || resultlen < 2)
2911
log_error ("apdu_send_direct(%d) failed: %s\n",
2912
slot, apdu_strerror (rc));
2914
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2916
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2917
/* Store away the returned data but strip the statusword. */
2921
log_debug (" response: sw=%04X datalen=%u\n",
2922
sw, (unsigned int)resultlen);
2923
if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2924
log_printhex (" dump: ", result, resultlen);
2927
if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
2929
unsigned char *p = NULL, *tmp;
2930
size_t bufsize = 4096;
2932
/* It is likely that we need to return much more data, so we
2933
start off with a large buffer. */
2936
*retbuf = p = xtrymalloc (bufsize + 2);
2940
return SW_HOST_OUT_OF_CORE;
2942
assert (resultlen < bufsize);
2943
memcpy (p, result, resultlen);
2949
int len = (sw & 0x00ff);
2952
log_debug ("apdu_send_direct(%d): %d more bytes available\n",
2955
apdu[apdulen++] = class;
2956
apdu[apdulen++] = 0xC0;
2957
apdu[apdulen++] = 0;
2958
apdu[apdulen++] = 0;
2959
apdu[apdulen++] = len;
2960
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2961
resultlen = RESULTLEN;
2962
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2963
if (rc || resultlen < 2)
2965
log_error ("apdu_send_direct(%d) for get response failed: %s\n",
2966
slot, apdu_strerror (rc));
2968
return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2970
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2974
log_debug (" more: sw=%04X datalen=%u\n",
2975
sw, (unsigned int)resultlen);
2976
if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2977
log_printhex (" dump: ", result, resultlen);
2980
if ((sw & 0xff00) == SW_MORE_DATA
2982
|| sw == SW_EOF_REACHED )
2984
if (retbuf && resultlen)
2986
if (p - *retbuf + resultlen > bufsize)
2988
bufsize += resultlen > 4096? resultlen: 4096;
2989
tmp = xtryrealloc (*retbuf, bufsize + 2);
2993
return SW_HOST_OUT_OF_CORE;
2995
p = tmp + (p - *retbuf);
2998
memcpy (p, result, resultlen);
3003
log_info ("apdu_send_sdirect(%d) "
3004
"got unexpected status %04X from get response\n",
3007
while ((sw & 0xff00) == SW_MORE_DATA);
3011
*retbuflen = p - *retbuf;
3012
tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3021
*retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3025
return SW_HOST_OUT_OF_CORE;
3027
*retbuflen = resultlen;
3028
memcpy (*retbuf, result, resultlen);
3034
/* Append the status word - we reseved the two extra bytes while
3035
allocating the buffer. */
3038
(*retbuf)[(*retbuflen)++] = (sw >> 8);
3039
(*retbuf)[(*retbuflen)++] = sw;
3042
if (DBG_CARD_IO && retbuf)
3043
log_printhex (" dump: ", *retbuf, *retbuflen);