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.4.2.24 2004/10/20 08:54:45 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
/* To to conflicting use of threading libraries we usually can't link
70
against libpcsclite. Instead we use a wrapper program. */
72
#ifndef HAVE_W32_SYSTEM
73
#define NEED_PCSC_WRAPPER 1
78
#define MAX_READER 4 /* Number of readers we support concurrently. */
82
#define DLSTDCALL __stdcall
87
#ifdef _POSIX_OPEN_MAX
88
#define MAX_OPEN_FDS _POSIX_OPEN_MAX
90
#define MAX_OPEN_FDS 20
94
/* A structure to collect information pertaining to one reader
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 (*close_reader)(int);
102
int (*shutdown_reader)(int);
103
int (*reset_reader)(int);
104
int (*get_status_reader)(int, unsigned int *);
105
int (*send_apdu_reader)(int,unsigned char *,size_t,
106
unsigned char *, size_t *);
107
void (*dump_status_reader)(int);
110
ccid_driver_t handle;
113
unsigned long context;
115
unsigned long protocol;
116
#ifdef NEED_PCSC_WRAPPER
120
#endif /*NEED_PCSC_WRAPPER*/
124
struct sc_context *ctx;
125
struct sc_card *scard;
127
#endif /*HAVE_OPENSC*/
128
#ifdef USE_G10CODE_RAPDU
132
#endif /*USE_G10CODE_RAPDU*/
133
char *rdrname; /* Name of the connected reader or NULL if unknown. */
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
140
unsigned int change_counter;
142
int lock_initialized;
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,
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. */
200
struct pcsc_io_request_s
202
unsigned long protocol;
203
unsigned long pci_len;
206
typedef struct pcsc_io_request_s *pcsc_io_request_t;
208
struct pcsc_readerstate_s
212
unsigned long current_state;
213
unsigned long event_state;
214
unsigned long atrlen;
215
unsigned char atr[33];
218
typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
220
long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
221
const void *reserved1,
222
const void *reserved2,
223
unsigned long *r_context);
224
long (* DLSTDCALL pcsc_release_context) (unsigned long context);
225
long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
227
char *readers, unsigned long*readerslen);
228
long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
229
unsigned long timeout,
230
pcsc_readerstate_t readerstates,
231
unsigned long nreaderstates);
232
long (* DLSTDCALL pcsc_connect) (unsigned long context,
234
unsigned long share_mode,
235
unsigned long preferred_protocols,
236
unsigned long *r_card,
237
unsigned long *r_active_protocol);
238
long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
239
unsigned long share_mode,
240
unsigned long preferred_protocols,
241
unsigned long initialization,
242
unsigned long *r_active_protocol);
243
long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
244
unsigned long disposition);
245
long (* DLSTDCALL pcsc_status) (unsigned long card,
246
char *reader, unsigned long *readerlen,
247
unsigned long *r_state,
248
unsigned long *r_protocol,
249
unsigned char *atr, unsigned long *atrlen);
250
long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
251
long (* DLSTDCALL pcsc_end_transaction) (unsigned long card);
252
long (* DLSTDCALL pcsc_transmit) (unsigned long card,
253
const pcsc_io_request_t send_pci,
254
const unsigned char *send_buffer,
255
unsigned long send_len,
256
pcsc_io_request_t recv_pci,
257
unsigned char *recv_buffer,
258
unsigned long *recv_len);
259
long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
260
unsigned long timeout);
270
/* Find an unused reader slot for PORTSTR and put it into the reader
271
table. Return -1 on error or the index into the reader table. */
273
new_reader_slot (void)
277
for (i=0; i < MAX_READER; i++)
279
if (!reader_table[i].used && reader == -1)
284
log_error ("new_reader_slot: out of slots\n");
288
if (!reader_table[reader].lock_initialized)
290
if (!pth_mutex_init (&reader_table[reader].lock))
292
log_error ("error initializing mutex: %s\n", strerror (errno));
295
reader_table[reader].lock_initialized = 1;
297
#endif /*USE_GNU_PTH*/
298
reader_table[reader].close_reader = NULL;
299
reader_table[reader].shutdown_reader = NULL;
300
reader_table[reader].reset_reader = NULL;
301
reader_table[reader].get_status_reader = NULL;
302
reader_table[reader].send_apdu_reader = NULL;
303
reader_table[reader].dump_status_reader = NULL;
305
reader_table[reader].used = 1;
306
reader_table[reader].last_status = 0;
307
#ifdef NEED_PCSC_WRAPPER
308
reader_table[reader].pcsc.req_fd = -1;
309
reader_table[reader].pcsc.rsp_fd = -1;
310
reader_table[reader].pcsc.pid = (pid_t)(-1);
318
dump_reader_status (int slot)
323
if (reader_table[slot].dump_status_reader)
324
reader_table[slot].dump_status_reader (slot);
326
if (reader_table[slot].status != -1
327
&& reader_table[slot].atrlen)
329
log_info ("slot %d: ATR=", slot);
330
log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
337
host_sw_string (long err)
341
case 0: return "okay";
342
case SW_HOST_OUT_OF_CORE: return "out of core";
343
case SW_HOST_INV_VALUE: return "invalid value";
344
case SW_HOST_NO_DRIVER: return "no driver";
345
case SW_HOST_NOT_SUPPORTED: return "not supported";
346
case SW_HOST_LOCKING_FAILED: return "locking failed";
347
case SW_HOST_BUSY: return "busy";
348
case SW_HOST_NO_CARD: return "no card";
349
case SW_HOST_CARD_INACTIVE: return "card inactive";
350
case SW_HOST_CARD_IO_ERROR: return "card I/O error";
351
case SW_HOST_GENERAL_ERROR: return "general error";
352
case SW_HOST_NO_READER: return "no reader";
353
case SW_HOST_ABORTED: return "aborted";
354
default: return "unknown host status error";
360
apdu_strerror (int rc)
364
case SW_EOF_REACHED : return "eof reached";
365
case SW_EEPROM_FAILURE : return "eeprom failure";
366
case SW_WRONG_LENGTH : return "wrong length";
367
case SW_CHV_WRONG : return "CHV wrong";
368
case SW_CHV_BLOCKED : return "CHV blocked";
369
case SW_USE_CONDITIONS : return "use conditions not satisfied";
370
case SW_BAD_PARAMETER : return "bad parameter";
371
case SW_NOT_SUPPORTED : return "not supported";
372
case SW_FILE_NOT_FOUND : return "file not found";
373
case SW_RECORD_NOT_FOUND:return "record not found";
374
case SW_REF_NOT_FOUND : return "reference not found";
375
case SW_BAD_P0_P1 : return "bad P0 or P1";
376
case SW_INS_NOT_SUP : return "instruction not supported";
377
case SW_CLA_NOT_SUP : return "class not supported";
378
case SW_SUCCESS : return "success";
380
if ((rc & ~0x00ff) == SW_MORE_DATA)
381
return "more data available";
382
if ( (rc & 0x10000) )
383
return host_sw_string (rc);
384
return "unknown status error";
395
ct_error_string (long err)
399
case 0: return "okay";
400
case -1: return "invalid data";
401
case -8: return "ct error";
402
case -10: return "transmission error";
403
case -11: return "memory allocation error";
404
case -128: return "HTSI error";
405
default: return "unknown CT-API error";
411
ct_dump_reader_status (int slot)
413
log_info ("reader slot %d: %s\n", slot,
414
reader_table[slot].status == 1? "Processor ICC present" :
415
reader_table[slot].status == 0? "Memory ICC present" :
420
/* Wait for the card in SLOT and activate it. Return a status word
421
error or 0 on success. */
423
ct_activate_card (int slot)
426
unsigned char dad[1], sad[1], cmd[11], buf[256];
427
unsigned short buflen;
429
/* Check whether card has been inserted. */
430
dad[0] = 1; /* Destination address: CT. */
431
sad[0] = 2; /* Source address: Host. */
433
cmd[0] = 0x20; /* Class byte. */
434
cmd[1] = 0x13; /* Request status. */
435
cmd[2] = 0x00; /* From kernel. */
436
cmd[3] = 0x80; /* Return card's DO. */
441
rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
442
if (rc || buflen < 2 || buf[buflen-2] != 0x90)
444
log_error ("ct_activate_card: can't get status of reader %d: %s\n",
445
slot, ct_error_string (rc));
446
return SW_HOST_CARD_IO_ERROR;
449
/* Connected, now activate the card. */
450
dad[0] = 1; /* Destination address: CT. */
451
sad[0] = 2; /* Source address: Host. */
453
cmd[0] = 0x20; /* Class byte. */
454
cmd[1] = 0x12; /* Request ICC. */
455
cmd[2] = 0x01; /* From first interface. */
456
cmd[3] = 0x01; /* Return card's ATR. */
461
rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
462
if (rc || buflen < 2 || buf[buflen-2] != 0x90)
464
log_error ("ct_activate_card(%d): activation failed: %s\n",
465
slot, ct_error_string (rc));
467
log_printhex (" received data:", buf, buflen);
468
return SW_HOST_CARD_IO_ERROR;
471
/* Store the type and the ATR. */
472
if (buflen - 2 > DIM (reader_table[0].atr))
474
log_error ("ct_activate_card(%d): ATR too long\n", slot);
475
return SW_HOST_CARD_IO_ERROR;
478
reader_table[slot].status = buf[buflen - 1];
479
memcpy (reader_table[slot].atr, buf, buflen - 2);
480
reader_table[slot].atrlen = buflen - 2;
486
close_ct_reader (int slot)
489
reader_table[slot].used = 0;
494
reset_ct_reader (int slot)
496
/* FIXME: Check is this is sufficient do do a reset. */
497
return ct_activate_card (slot);
502
ct_get_status (int slot, unsigned int *status)
504
*status = 1|2|4; /* FIXME */
507
return SW_HOST_NOT_SUPPORTED;
510
/* Actually send the APDU of length APDULEN to SLOT and return a
511
maximum of *BUFLEN data in BUFFER, the actual retruned size will be
512
set to BUFLEN. Returns: CT API error code. */
514
ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
515
unsigned char *buffer, size_t *buflen)
518
unsigned char dad[1], sad[1];
519
unsigned short ctbuflen;
521
/* If we don't have an ATR, we need to reset the reader first. */
522
if (!reader_table[slot].atrlen
523
&& (rc = reset_ct_reader (slot)))
526
dad[0] = 0; /* Destination address: Card. */
527
sad[0] = 2; /* Source address: Host. */
530
log_printhex (" CT_data:", apdu, apdulen);
531
rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
534
return rc? SW_HOST_CARD_IO_ERROR: 0;
539
/* Open a reader and return an internal handle for it. PORT is a
540
non-negative value with the port number of the reader. USB readers
541
do have port numbers starting at 32769. */
543
open_ct_reader (int port)
547
if (port < 0 || port > 0xffff)
549
log_error ("open_ct_reader: invalid port %d requested\n", port);
552
reader = new_reader_slot ();
555
reader_table[reader].port = port;
557
rc = CT_init (reader, (unsigned short)port);
560
log_error ("apdu_open_ct_reader failed on port %d: %s\n",
561
port, ct_error_string (rc));
562
reader_table[reader].used = 0;
566
/* Only try to activate the card. */
567
rc = ct_activate_card (reader);
570
reader_table[reader].atrlen = 0;
574
reader_table[reader].close_reader = close_ct_reader;
575
reader_table[reader].reset_reader = reset_ct_reader;
576
reader_table[reader].get_status_reader = ct_get_status;
577
reader_table[reader].send_apdu_reader = ct_send_apdu;
578
reader_table[reader].dump_status_reader = ct_dump_reader_status;
580
dump_reader_status (reader);
585
#ifdef NEED_PCSC_WRAPPER
587
writen (int fd, const void *buf, size_t nbytes)
589
size_t nleft = nbytes;
592
/* log_printhex (" writen:", buf, nbytes); */
597
nwritten = pth_write (fd, buf, nleft);
599
nwritten = write (fd, buf, nleft);
601
if (nwritten < 0 && errno == EINTR)
606
buf = (const char*)buf + nwritten;
611
/* Read up to BUFLEN bytes from FD and return the number of bytes
612
actually read in NREAD. Returns -1 on error or 0 on success. */
614
readn (int fd, void *buf, size_t buflen, size_t *nread)
616
size_t nleft = buflen;
618
/* void *orig_buf = buf; */
623
n = pth_read (fd, buf, nleft);
625
n = read (fd, buf, nleft);
627
if (n < 0 && errno == EINTR)
630
return -1; /* read error. */
634
buf = (char*)buf + n;
637
*nread = buflen - nleft;
639
/* log_printhex (" readn:", orig_buf, *nread); */
643
#endif /*NEED_PCSC_WRAPPER*/
646
pcsc_error_string (long err)
652
if ((err & 0x80100000) != 0x80100000)
653
return "invalid PC/SC error code";
657
case 0x0002: s = "cancelled"; break;
658
case 0x000e: s = "can't dispose"; break;
659
case 0x0008: s = "insufficient buffer"; break;
660
case 0x0015: s = "invalid ATR"; break;
661
case 0x0003: s = "invalid handle"; break;
662
case 0x0004: s = "invalid parameter"; break;
663
case 0x0005: s = "invalid target"; break;
664
case 0x0011: s = "invalid value"; break;
665
case 0x0006: s = "no memory"; break;
666
case 0x0013: s = "comm error"; break;
667
case 0x0001: s = "internal error"; break;
668
case 0x0014: s = "unknown error"; break;
669
case 0x0007: s = "waited too long"; break;
670
case 0x0009: s = "unknown reader"; break;
671
case 0x000a: s = "timeout"; break;
672
case 0x000b: s = "sharing violation"; break;
673
case 0x000c: s = "no smartcard"; break;
674
case 0x000d: s = "unknown card"; break;
675
case 0x000f: s = "proto mismatch"; break;
676
case 0x0010: s = "not ready"; break;
677
case 0x0012: s = "system cancelled"; break;
678
case 0x0016: s = "not transacted"; break;
679
case 0x0017: s = "reader unavailable"; break;
680
case 0x0065: s = "unsupported card"; break;
681
case 0x0066: s = "unresponsive card"; break;
682
case 0x0067: s = "unpowered card"; break;
683
case 0x0068: s = "reset card"; break;
684
case 0x0069: s = "removed card"; break;
685
case 0x006a: s = "inserted card"; break;
686
case 0x001f: s = "unsupported feature"; break;
687
case 0x0019: s = "PCI too small"; break;
688
case 0x001a: s = "reader unsupported"; break;
689
case 0x001b: s = "duplicate reader"; break;
690
case 0x001c: s = "card unsupported"; break;
691
case 0x001d: s = "no service"; break;
692
case 0x001e: s = "service stopped"; break;
693
default: s = "unknown PC/SC error code"; break;
703
dump_pcsc_reader_status (int slot)
705
log_info ("reader slot %d: active protocol:", slot);
706
if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
708
else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
710
else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
717
reset_pcsc_reader (int slot)
719
#ifdef NEED_PCSC_WRAPPER
721
reader_table_t slotp;
724
unsigned char msgbuf[9];
726
slotp = reader_table + slot;
728
if (slotp->pcsc.req_fd == -1
729
|| slotp->pcsc.rsp_fd == -1
730
|| slotp->pcsc.pid == (pid_t)(-1) )
732
log_error ("pcsc_get_status: pcsc-wrapper not running\n");
733
return SW_HOST_CARD_IO_ERROR;
736
msgbuf[0] = 0x05; /* RESET command. */
738
msgbuf[1] = (len >> 24);
739
msgbuf[2] = (len >> 16);
740
msgbuf[3] = (len >> 8);
742
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
744
log_error ("error sending PC/SC RESET request: %s\n",
749
/* Read the response. */
750
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
752
log_error ("error receiving PC/SC RESET response: %s\n",
753
i? strerror (errno) : "premature EOF");
756
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
757
if (msgbuf[0] != 0x81 || len < 4)
759
log_error ("invalid response header from PC/SC received\n");
762
len -= 4; /* Already read the error code. */
763
if (len > DIM (slotp->atr))
765
log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
768
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
771
log_error ("PC/SC RESET failed: %s\n", pcsc_error_string (err));
775
/* The open fucntion may return a zero for the ATR length to
776
indicate that no card is present. */
780
if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
782
log_error ("error receiving PC/SC RESET response: %s\n",
783
i? strerror (errno) : "premature EOF");
792
close (slotp->pcsc.req_fd);
793
close (slotp->pcsc.rsp_fd);
794
slotp->pcsc.req_fd = -1;
795
slotp->pcsc.rsp_fd = -1;
796
kill (slotp->pcsc.pid, SIGTERM);
797
slotp->pcsc.pid = (pid_t)(-1);
801
#else /* !NEED_PCSC_WRAPPER */
804
unsigned long nreader, atrlen;
805
unsigned long card_state, card_protocol;
807
if (reader_table[slot].pcsc.card)
809
err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
812
log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
813
pcsc_error_string (err), err);
814
return SW_HOST_CARD_IO_ERROR;
816
reader_table[slot].pcsc.card = 0;
819
err = pcsc_connect (reader_table[slot].pcsc.context,
820
reader_table[slot].rdrname,
821
PCSC_SHARE_EXCLUSIVE,
822
PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
823
&reader_table[slot].pcsc.card,
824
&reader_table[slot].pcsc.protocol);
827
log_error ("pcsc_connect failed: %s (0x%lx)\n",
828
pcsc_error_string (err), err);
829
reader_table[slot].pcsc.card = 0;
830
return SW_HOST_CARD_IO_ERROR;
835
nreader = sizeof reader - 1;
836
err = pcsc_status (reader_table[slot].pcsc.card,
838
&card_state, &card_protocol,
839
reader_table[slot].atr, &atrlen);
842
log_error ("pcsc_status failed: %s (0x%lx)\n",
843
pcsc_error_string (err), err);
844
reader_table[slot].atrlen = 0;
845
return SW_HOST_CARD_IO_ERROR;
847
if (atrlen >= DIM (reader_table[0].atr))
848
log_bug ("ATR returned by pcsc_status is too large\n");
849
reader_table[slot].atrlen = atrlen;
852
#endif /* !NEED_PCSC_WRAPPER */
857
pcsc_get_status (int slot, unsigned int *status)
859
#ifdef NEED_PCSC_WRAPPER
861
reader_table_t slotp;
862
size_t len, full_len;
864
unsigned char msgbuf[9];
865
unsigned char buffer[12];
867
slotp = reader_table + slot;
869
if (slotp->pcsc.req_fd == -1
870
|| slotp->pcsc.rsp_fd == -1
871
|| slotp->pcsc.pid == (pid_t)(-1) )
873
log_error ("pcsc_get_status: pcsc-wrapper not running\n");
874
return SW_HOST_CARD_IO_ERROR;
877
msgbuf[0] = 0x04; /* STATUS command. */
879
msgbuf[1] = (len >> 24);
880
msgbuf[2] = (len >> 16);
881
msgbuf[3] = (len >> 8);
883
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
885
log_error ("error sending PC/SC STATUS request: %s\n",
890
/* Read the response. */
891
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
893
log_error ("error receiving PC/SC STATUS response: %s\n",
894
i? strerror (errno) : "premature EOF");
897
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
898
if (msgbuf[0] != 0x81 || len < 4)
900
log_error ("invalid response header from PC/SC received\n");
903
len -= 4; /* Already read the error code. */
904
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
907
log_error ("pcsc_status failed: %s (0x%lx)\n",
908
pcsc_error_string (err), err);
909
return SW_HOST_CARD_IO_ERROR;
914
n = 8 < len ? 8 : len;
915
if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != 8)
917
log_error ("error receiving PC/SC STATUS response: %s\n",
918
i? strerror (errno) : "premature EOF");
923
/* Newer versions of the wrapper might send more status bytes.
927
unsigned char dummybuf[128];
929
n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
930
if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
932
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
933
i? strerror (errno) : "premature EOF");
939
/* We are lucky: The wrapper already returns the data in the
946
close (slotp->pcsc.req_fd);
947
close (slotp->pcsc.rsp_fd);
948
slotp->pcsc.req_fd = -1;
949
slotp->pcsc.rsp_fd = -1;
950
kill (slotp->pcsc.pid, SIGTERM);
951
slotp->pcsc.pid = (pid_t)(-1);
955
#else /*!NEED_PCSC_WRAPPER*/
958
struct pcsc_readerstate_s rdrstates[1];
960
memset (rdrstates, 0, sizeof *rdrstates);
961
rdrstates[0].reader = reader_table[slot].rdrname;
962
rdrstates[0].current_state = PCSC_STATE_UNAWARE;
963
err = pcsc_get_status_change (reader_table[slot].pcsc.context,
966
if (err == 0x8010000a) /* Timeout. */
970
log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
971
pcsc_error_string (err), err);
972
return SW_HOST_CARD_IO_ERROR;
977
/* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
978
/* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
979
/* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
980
/* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
981
/* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
982
/* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
983
/* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
984
/* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
985
/* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
986
/* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
987
/* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
990
if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
992
if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
994
/* We indicate a useful card if it is not in use by another
995
application. This is because we only use exclusive access
997
if ( (*status & 6) == 6
998
&& !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
1002
#endif /*!NEED_PCSC_WRAPPER*/
1006
/* Actually send the APDU of length APDULEN to SLOT and return a
1007
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1008
set to BUFLEN. Returns: CT API error code. */
1010
pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1011
unsigned char *buffer, size_t *buflen)
1013
#ifdef NEED_PCSC_WRAPPER
1015
reader_table_t slotp;
1016
size_t len, full_len;
1018
unsigned char msgbuf[9];
1020
if (!reader_table[slot].atrlen
1021
&& (err = reset_pcsc_reader (slot)))
1025
log_printhex (" PCSC_data:", apdu, apdulen);
1027
slotp = reader_table + slot;
1029
if (slotp->pcsc.req_fd == -1
1030
|| slotp->pcsc.rsp_fd == -1
1031
|| slotp->pcsc.pid == (pid_t)(-1) )
1033
log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1034
return SW_HOST_CARD_IO_ERROR;
1037
msgbuf[0] = 0x03; /* TRANSMIT command. */
1039
msgbuf[1] = (len >> 24);
1040
msgbuf[2] = (len >> 16);
1041
msgbuf[3] = (len >> 8);
1043
if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1044
|| writen (slotp->pcsc.req_fd, apdu, len))
1046
log_error ("error sending PC/SC TRANSMIT request: %s\n",
1048
goto command_failed;
1051
/* Read the response. */
1052
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1054
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1055
i? strerror (errno) : "premature EOF");
1056
goto command_failed;
1058
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1059
if (msgbuf[0] != 0x81 || len < 4)
1061
log_error ("invalid response header from PC/SC received\n");
1062
goto command_failed;
1064
len -= 4; /* Already read the error code. */
1065
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1068
log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1069
pcsc_error_string (err), err);
1070
return SW_HOST_CARD_IO_ERROR;
1075
n = *buflen < len ? *buflen : len;
1076
if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1078
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1079
i? strerror (errno) : "premature EOF");
1080
goto command_failed;
1087
log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1088
err = SW_HOST_INV_VALUE;
1090
/* We need to read any rest of the response, to keep the
1094
unsigned char dummybuf[128];
1096
n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1097
if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1099
log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1100
i? strerror (errno) : "premature EOF");
1101
goto command_failed;
1109
close (slotp->pcsc.req_fd);
1110
close (slotp->pcsc.rsp_fd);
1111
slotp->pcsc.req_fd = -1;
1112
slotp->pcsc.rsp_fd = -1;
1113
kill (slotp->pcsc.pid, SIGTERM);
1114
slotp->pcsc.pid = (pid_t)(-1);
1118
#else /*!NEED_PCSC_WRAPPER*/
1121
struct pcsc_io_request_s send_pci;
1122
unsigned long recv_len;
1124
if (!reader_table[slot].atrlen
1125
&& (err = reset_pcsc_reader (slot)))
1129
log_printhex (" PCSC_data:", apdu, apdulen);
1131
if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1132
send_pci.protocol = PCSC_PROTOCOL_T1;
1134
send_pci.protocol = PCSC_PROTOCOL_T0;
1135
send_pci.pci_len = sizeof send_pci;
1137
err = pcsc_transmit (reader_table[slot].pcsc.card,
1138
&send_pci, apdu, apdulen,
1139
NULL, buffer, &recv_len);
1142
log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1143
pcsc_error_string (err), err);
1145
return err? SW_HOST_CARD_IO_ERROR:0;
1146
#endif /*!NEED_PCSC_WRAPPER*/
1151
close_pcsc_reader (int slot)
1153
#ifdef NEED_PCSC_WRAPPER
1155
reader_table_t slotp;
1158
unsigned char msgbuf[9];
1160
slotp = reader_table + slot;
1162
if (slotp->pcsc.req_fd == -1
1163
|| slotp->pcsc.rsp_fd == -1
1164
|| slotp->pcsc.pid == (pid_t)(-1) )
1166
log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1170
msgbuf[0] = 0x02; /* CLOSE command. */
1172
msgbuf[1] = (len >> 24);
1173
msgbuf[2] = (len >> 16);
1174
msgbuf[3] = (len >> 8);
1176
if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1178
log_error ("error sending PC/SC CLOSE request: %s\n",
1180
goto command_failed;
1183
/* Read the response. */
1184
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1186
log_error ("error receiving PC/SC CLOSE response: %s\n",
1187
i? strerror (errno) : "premature EOF");
1188
goto command_failed;
1190
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1191
if (msgbuf[0] != 0x81 || len < 4)
1193
log_error ("invalid response header from PC/SC received\n");
1194
goto command_failed;
1196
len -= 4; /* Already read the error code. */
1197
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1199
log_error ("pcsc_close failed: %s (0x%lx)\n",
1200
pcsc_error_string (err), err);
1202
/* We will the wrapper in any case - errors are merely
1206
close (slotp->pcsc.req_fd);
1207
close (slotp->pcsc.rsp_fd);
1208
slotp->pcsc.req_fd = -1;
1209
slotp->pcsc.rsp_fd = -1;
1210
kill (slotp->pcsc.pid, SIGTERM);
1211
slotp->pcsc.pid = (pid_t)(-1);
1215
#else /*!NEED_PCSC_WRAPPER*/
1217
pcsc_release_context (reader_table[slot].pcsc.context);
1218
xfree (reader_table[slot].rdrname);
1219
reader_table[slot].rdrname = NULL;
1220
reader_table[slot].used = 0;
1222
#endif /*!NEED_PCSC_WRAPPER*/
1226
open_pcsc_reader (const char *portstr)
1228
#ifdef NEED_PCSC_WRAPPER
1229
/* Open the PC/SC reader using the pcsc_wrapper program. This is
1230
needed to cope with different thread models and other peculiarities
1233
reader_table_t slotp;
1234
int fd, rp[2], wp[2];
1238
unsigned char msgbuf[9];
1241
slot = new_reader_slot ();
1244
slotp = reader_table + slot;
1246
/* Fire up the pcsc wrapper. We don't use any fork/exec code from
1247
the common directy but implement it direclty so that this file
1248
may still be source copied. */
1250
if (pipe (rp) == -1)
1252
log_error ("error creating a pipe: %s\n", strerror (errno));
1256
if (pipe (wp) == -1)
1258
log_error ("error creating a pipe: %s\n", strerror (errno));
1268
log_error ("error forking process: %s\n", strerror (errno));
1276
slotp->pcsc.pid = pid;
1288
_exit (0); /* Immediate exit this parent, so that the child
1289
gets cleaned up by the init process. */
1291
/* Connect our pipes. */
1292
if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1293
log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1294
if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1295
log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1297
/* Send stderr to the bit bucket. */
1298
fd = open ("/dev/null", O_WRONLY);
1300
log_fatal ("can't open `/dev/null': %s", strerror (errno));
1301
if (fd != 2 && dup2 (fd, 2) == -1)
1302
log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1304
/* Close all other files. */
1305
n = sysconf (_SC_OPEN_MAX);
1308
for (i=3; i < n; i++)
1312
execl (GNUPG_LIBDIR "/pcsc-wrapper",
1315
"1", /* API version */
1316
opt.pcsc_driver, /* Name of the PC/SC library. */
1326
slotp->pcsc.req_fd = wp[1];
1327
slotp->pcsc.rsp_fd = rp[0];
1329
/* Wait for the intermediate child to terminate. */
1331
#define WAIT pth_waitpid
1333
#define WAIT waitpid
1335
while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1339
/* Now send the open request. */
1340
msgbuf[0] = 0x01; /* OPEN command. */
1341
len = portstr? strlen (portstr):0;
1342
msgbuf[1] = (len >> 24);
1343
msgbuf[2] = (len >> 16);
1344
msgbuf[3] = (len >> 8);
1346
if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1347
|| (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1349
log_error ("error sending PC/SC OPEN request: %s\n",
1351
goto command_failed;
1353
/* Read the response. */
1354
if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1356
log_error ("error receiving PC/SC OPEN response: %s\n",
1357
i? strerror (errno) : "premature EOF");
1358
goto command_failed;
1360
len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1361
if (msgbuf[0] != 0x81 || len < 4)
1363
log_error ("invalid response header from PC/SC received\n");
1364
goto command_failed;
1366
len -= 4; /* Already read the error code. */
1367
if (len > DIM (slotp->atr))
1369
log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
1370
goto command_failed;
1372
err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
1375
log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1376
goto command_failed;
1379
slotp->last_status = 0;
1381
/* The open fucntion may return a zero for the ATR length to
1382
indicate that no card is present. */
1386
if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1388
log_error ("error receiving PC/SC OPEN response: %s\n",
1389
i? strerror (errno) : "premature EOF");
1390
goto command_failed;
1392
/* If we got to here we know that a card is present
1393
and usable. Thus remember this. */
1394
slotp->last_status = (1|2|4| 0x8000);
1396
slotp->atrlen = len;
1398
reader_table[slot].close_reader = close_pcsc_reader;
1399
reader_table[slot].reset_reader = reset_pcsc_reader;
1400
reader_table[slot].get_status_reader = pcsc_get_status;
1401
reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1402
reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1404
dump_reader_status (slot);
1408
close (slotp->pcsc.req_fd);
1409
close (slotp->pcsc.rsp_fd);
1410
slotp->pcsc.req_fd = -1;
1411
slotp->pcsc.rsp_fd = -1;
1412
kill (slotp->pcsc.pid, SIGTERM);
1413
slotp->pcsc.pid = (pid_t)(-1);
1416
#else /*!NEED_PCSC_WRAPPER */
1420
unsigned long nreader, listlen, atrlen;
1422
unsigned long card_state, card_protocol;
1424
slot = new_reader_slot ();
1428
err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1429
&reader_table[slot].pcsc.context);
1432
log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1433
pcsc_error_string (err), err);
1434
reader_table[slot].used = 0;
1438
err = pcsc_list_readers (reader_table[slot].pcsc.context,
1439
NULL, NULL, &nreader);
1442
list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1445
log_error ("error allocating memory for reader list\n");
1446
pcsc_release_context (reader_table[slot].pcsc.context);
1447
reader_table[slot].used = 0;
1450
err = pcsc_list_readers (reader_table[slot].pcsc.context,
1451
NULL, list, &nreader);
1455
log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1456
pcsc_error_string (err), err);
1457
pcsc_release_context (reader_table[slot].pcsc.context);
1458
reader_table[slot].used = 0;
1470
log_info ("detected reader `%s'\n", p);
1471
if (nreader < (strlen (p)+1))
1473
log_error ("invalid response from pcsc_list_readers\n");
1476
nreader -= strlen (p)+1;
1477
p += strlen (p) + 1;
1480
reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1481
if (!reader_table[slot].rdrname)
1483
log_error ("error allocating memory for reader name\n");
1484
pcsc_release_context (reader_table[slot].pcsc.context);
1485
reader_table[slot].used = 0;
1488
strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1491
err = pcsc_connect (reader_table[slot].pcsc.context,
1492
reader_table[slot].rdrname,
1493
PCSC_SHARE_EXCLUSIVE,
1494
PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1495
&reader_table[slot].pcsc.card,
1496
&reader_table[slot].pcsc.protocol);
1497
if (err == 0x8010000c) /* No smartcard. */
1498
reader_table[slot].pcsc.card = 0;
1501
log_error ("pcsc_connect failed: %s (0x%lx)\n",
1502
pcsc_error_string (err), err);
1503
pcsc_release_context (reader_table[slot].pcsc.context);
1504
xfree (reader_table[slot].rdrname);
1505
reader_table[slot].rdrname = NULL;
1506
reader_table[slot].used = 0;
1511
reader_table[slot].atrlen = 0;
1512
reader_table[slot].last_status = 0;
1516
unsigned long readerlen;
1519
readerlen = sizeof reader -1 ;
1520
err = pcsc_status (reader_table[slot].pcsc.card,
1522
&card_state, &card_protocol,
1523
reader_table[slot].atr, &atrlen);
1525
log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1526
pcsc_error_string (err), err, readerlen);
1529
if (atrlen >= DIM (reader_table[0].atr))
1530
log_bug ("ATR returned by pcsc_status is too large\n");
1531
reader_table[slot].atrlen = atrlen;
1532
/* If we got to here we know that a card is present
1533
and usable. Thus remember this. */
1534
reader_table[slot].last_status = (1|2|4| 0x8000);
1538
reader_table[slot].close_reader = close_pcsc_reader;
1539
reader_table[slot].reset_reader = reset_pcsc_reader;
1540
reader_table[slot].get_status_reader = pcsc_get_status;
1541
reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1542
reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1544
/* log_debug ("state from pcsc_status: 0x%lx\n", card_state); */
1545
/* log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
1547
dump_reader_status (slot);
1549
#endif /*!NEED_PCSC_WRAPPER */
1557
Internal CCID driver interface.
1562
dump_ccid_reader_status (int slot)
1564
log_info ("reader slot %d: using ccid driver\n", slot);
1568
close_ccid_reader (int slot)
1570
ccid_close_reader (reader_table[slot].ccid.handle);
1571
reader_table[slot].used = 0;
1577
shutdown_ccid_reader (int slot)
1579
ccid_shutdown_reader (reader_table[slot].ccid.handle);
1585
reset_ccid_reader (int slot)
1588
reader_table_t slotp = reader_table + slot;
1589
unsigned char atr[33];
1592
err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1595
/* If the reset was successful, update the ATR. */
1596
assert (sizeof slotp->atr >= sizeof atr);
1597
slotp->atrlen = atrlen;
1598
memcpy (slotp->atr, atr, atrlen);
1599
dump_reader_status (slot);
1605
get_status_ccid (int slot, unsigned int *status)
1610
rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1625
/* Actually send the APDU of length APDULEN to SLOT and return a
1626
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1627
set to BUFLEN. Returns: Internal CCID driver error code. */
1629
send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1630
unsigned char *buffer, size_t *buflen)
1635
/* If we don't have an ATR, we need to reset the reader first. */
1636
if (!reader_table[slot].atrlen
1637
&& (err = reset_ccid_reader (slot)))
1641
log_printhex (" APDU_data:", apdu, apdulen);
1643
maxbuflen = *buflen;
1644
err = ccid_transceive (reader_table[slot].ccid.handle,
1646
buffer, maxbuflen, buflen);
1648
log_error ("ccid_transceive failed: (0x%lx)\n",
1654
/* Open the reader and try to read an ATR. */
1656
open_ccid_reader (const char *portstr)
1660
reader_table_t slotp;
1662
slot = new_reader_slot ();
1665
slotp = reader_table + slot;
1667
err = ccid_open_reader (&slotp->ccid.handle, portstr);
1674
err = ccid_get_atr (slotp->ccid.handle,
1675
slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1683
/* If we got to here we know that a card is present
1684
and usable. Thus remember this. */
1685
reader_table[slot].last_status = (1|2|4| 0x8000);
1688
reader_table[slot].close_reader = close_ccid_reader;
1689
reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1690
reader_table[slot].reset_reader = reset_ccid_reader;
1691
reader_table[slot].get_status_reader = get_status_ccid;
1692
reader_table[slot].send_apdu_reader = send_apdu_ccid;
1693
reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1695
dump_reader_status (slot);
1701
#endif /* HAVE_LIBUSB */
1709
This uses the OpenSC primitives to send APDUs. We need this
1710
because we can't mix OpenSC and native (i.e. ctAPI or PC/SC)
1711
access to a card for resource conflict reasons.
1716
close_osc_reader (int slot)
1718
/* FIXME: Implement. */
1719
reader_table[slot].used = 0;
1724
reset_osc_reader (int slot)
1726
return SW_HOST_NOT_SUPPORTED;
1731
osc_get_status (int slot, unsigned int *status)
1733
return SW_HOST_NOT_SUPPORTED;
1737
/* Actually send the APDU of length APDULEN to SLOT and return a
1738
maximum of *BUFLEN data in BUFFER, the actual returned size will be
1739
set to BUFLEN. Returns: OpenSC error code. */
1741
osc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1742
unsigned char *buffer, size_t *buflen)
1746
unsigned char data[SC_MAX_APDU_BUFFER_SIZE];
1747
unsigned char result[SC_MAX_APDU_BUFFER_SIZE];
1750
log_printhex (" APDU_data:", apdu, apdulen);
1754
log_error ("osc_send_apdu: APDU is too short\n");
1755
return SW_HOST_INV_VALUE;
1758
memset(&a, 0, sizeof a);
1766
a.cse = SC_APDU_CASE_1;
1767
else if (apdulen == 1)
1769
a.le = *apdu? *apdu : 256;
1771
a.cse = SC_APDU_CASE_2_SHORT;
1775
a.lc = *apdu++; apdulen--;
1778
log_error ("osc_send_apdu: APDU shorter than specified in Lc\n");
1779
return SW_HOST_INV_VALUE;
1782
memcpy(data, apdu, a.lc);
1783
apdu += a.lc; apdulen -= a.lc;
1789
a.cse = SC_APDU_CASE_3_SHORT;
1792
a.le = *apdu? *apdu : 256;
1796
log_error ("osc_send_apdu: APDU larger than specified\n");
1797
return SW_HOST_INV_VALUE;
1799
a.cse = SC_APDU_CASE_4_SHORT;
1804
a.resplen = DIM(result);
1806
err = sc_transmit_apdu (reader_table[slot].osc.scard, &a);
1809
log_error ("sc_apdu_transmit failed: %s\n", sc_strerror (err));
1810
return SW_HOST_CARD_IO_ERROR;
1813
if (*buflen < 2 || a.resplen > *buflen - 2)
1815
log_error ("osc_send_apdu: provided buffer too short to store result\n");
1816
return SW_HOST_INV_VALUE;
1818
memcpy (buffer, a.resp, a.resplen);
1819
buffer[a.resplen] = a.sw1;
1820
buffer[a.resplen+1] = a.sw2;
1821
*buflen = a.resplen + 2;
1826
open_osc_reader (int portno)
1830
reader_table_t slotp;
1832
slot = new_reader_slot ();
1835
slotp = reader_table + slot;
1837
err = sc_establish_context (&slotp->osc.ctx, "scdaemon");
1840
log_error ("failed to establish SC context: %s\n", sc_strerror (err));
1844
if (portno < 0 || portno >= slotp->osc.ctx->reader_count)
1846
log_error ("no card reader available\n");
1847
sc_release_context (slotp->osc.ctx);
1852
/* Redirect to our logging facility. */
1853
slotp->osc.ctx->error_file = log_get_stream ();
1854
slotp->osc.ctx->debug = opt.debug_sc;
1855
slotp->osc.ctx->debug_file = log_get_stream ();
1857
if (sc_detect_card_presence (slotp->osc.ctx->reader[portno], 0) != 1)
1859
log_error ("no card present\n");
1860
sc_release_context (slotp->osc.ctx);
1865
/* We want the standard ISO driver. */
1866
/*FIXME: OpenSC does not like "iso7816", so we use EMV for now. */
1867
err = sc_set_card_driver(slotp->osc.ctx, "emv");
1870
log_error ("failed to select the iso7816 driver: %s\n",
1872
sc_release_context (slotp->osc.ctx);
1877
/* Now connect the card and hope that OpenSC won't try to be too
1879
err = sc_connect_card (slotp->osc.ctx->reader[portno], 0,
1883
log_error ("failed to connect card in reader %d: %s\n",
1884
portno, sc_strerror (err));
1885
sc_release_context (slotp->osc.ctx);
1890
log_info ("connected to card in opensc reader %d using driver `%s'\n",
1891
portno, slotp->osc.scard->driver->name);
1893
err = sc_lock (slotp->osc.scard);
1896
log_error ("can't lock card in reader %d: %s\n",
1897
portno, sc_strerror (err));
1898
sc_disconnect_card (slotp->osc.scard, 0);
1899
sc_release_context (slotp->osc.ctx);
1904
if (slotp->osc.scard->atr_len >= DIM (slotp->atr))
1905
log_bug ("ATR returned by opensc is too large\n");
1906
slotp->atrlen = slotp->osc.scard->atr_len;
1907
memcpy (slotp->atr, slotp->osc.scard->atr, slotp->atrlen);
1909
reader_table[slot].close_reader = close_osc_reader;
1910
reader_table[slot].reset_reader = reset_osc_reader;
1911
reader_table[slot].get_status_reader = osc_get_status;
1912
reader_table[slot].send_apdu_reader = osc_send_apdu;
1913
reader_table[slot].dump_status_reader = NULL;
1915
dump_reader_status (slot);
1919
#endif /* HAVE_OPENSC */
1923
#ifdef USE_G10CODE_RAPDU
1925
The Remote APDU Interface.
1927
This uses the Remote APDU protocol to contact a reader.
1929
The port number is actually an index into the list of ports as
1930
returned via the protocol.
1935
rapdu_status_to_sw (int status)
1941
case RAPDU_STATUS_SUCCESS: rc = 0; break;
1943
case RAPDU_STATUS_INVCMD:
1944
case RAPDU_STATUS_INVPROT:
1945
case RAPDU_STATUS_INVSEQ:
1946
case RAPDU_STATUS_INVCOOKIE:
1947
case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1949
case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1950
case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1951
case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1952
case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1953
case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1954
case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1956
default: rc = SW_HOST_GENERAL_ERROR; break;
1965
close_rapdu_reader (int slot)
1967
rapdu_release (reader_table[slot].rapdu.handle);
1968
reader_table[slot].used = 0;
1974
reset_rapdu_reader (int slot)
1977
reader_table_t slotp;
1978
rapdu_msg_t msg = NULL;
1980
slotp = reader_table + slot;
1982
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1985
log_error ("sending rapdu command RESET failed: %s\n",
1986
err < 0 ? strerror (errno): rapdu_strerror (err));
1987
rapdu_msg_release (msg);
1988
return rapdu_status_to_sw (err);
1990
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1993
log_error ("receiving rapdu message failed: %s\n",
1994
err < 0 ? strerror (errno): rapdu_strerror (err));
1995
rapdu_msg_release (msg);
1996
return rapdu_status_to_sw (err);
1998
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2000
int sw = rapdu_status_to_sw (msg->cmd);
2001
log_error ("rapdu command RESET failed: %s\n",
2002
rapdu_strerror (msg->cmd));
2003
rapdu_msg_release (msg);
2006
if (msg->datalen >= DIM (slotp->atr))
2008
log_error ("ATR returned by the RAPDU layer is too large\n");
2009
rapdu_msg_release (msg);
2010
return SW_HOST_INV_VALUE;
2012
slotp->atrlen = msg->datalen;
2013
memcpy (slotp->atr, msg->data, msg->datalen);
2015
rapdu_msg_release (msg);
2021
my_rapdu_get_status (int slot, unsigned int *status)
2024
reader_table_t slotp;
2025
rapdu_msg_t msg = NULL;
2028
slotp = reader_table + slot;
2030
oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2031
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2032
rapdu_set_reader (slotp->rapdu.handle, oldslot);
2035
log_error ("sending rapdu command GET_STATUS failed: %s\n",
2036
err < 0 ? strerror (errno): rapdu_strerror (err));
2037
return rapdu_status_to_sw (err);
2039
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2042
log_error ("receiving rapdu message failed: %s\n",
2043
err < 0 ? strerror (errno): rapdu_strerror (err));
2044
rapdu_msg_release (msg);
2045
return rapdu_status_to_sw (err);
2047
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2049
int sw = rapdu_status_to_sw (msg->cmd);
2050
log_error ("rapdu command GET_STATUS failed: %s\n",
2051
rapdu_strerror (msg->cmd));
2052
rapdu_msg_release (msg);
2055
*status = msg->data[0];
2057
rapdu_msg_release (msg);
2062
/* Actually send the APDU of length APDULEN to SLOT and return a
2063
maximum of *BUFLEN data in BUFFER, the actual returned size will be
2064
set to BUFLEN. Returns: OpenSC error code. */
2066
my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2067
unsigned char *buffer, size_t *buflen)
2070
reader_table_t slotp;
2071
rapdu_msg_t msg = NULL;
2072
size_t maxlen = *buflen;
2074
slotp = reader_table + slot;
2078
log_printhex (" APDU_data:", apdu, apdulen);
2082
log_error ("rapdu_send_apdu: APDU is too short\n");
2083
return SW_HOST_INV_VALUE;
2086
err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2089
log_error ("sending rapdu command APDU failed: %s\n",
2090
err < 0 ? strerror (errno): rapdu_strerror (err));
2091
rapdu_msg_release (msg);
2092
return rapdu_status_to_sw (err);
2094
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2097
log_error ("receiving rapdu message failed: %s\n",
2098
err < 0 ? strerror (errno): rapdu_strerror (err));
2099
rapdu_msg_release (msg);
2100
return rapdu_status_to_sw (err);
2102
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2104
int sw = rapdu_status_to_sw (msg->cmd);
2105
log_error ("rapdu command APDU failed: %s\n",
2106
rapdu_strerror (msg->cmd));
2107
rapdu_msg_release (msg);
2111
if (msg->datalen > maxlen)
2113
log_error ("rapdu response apdu too large\n");
2114
rapdu_msg_release (msg);
2115
return SW_HOST_INV_VALUE;
2118
*buflen = msg->datalen;
2119
memcpy (buffer, msg->data, msg->datalen);
2121
rapdu_msg_release (msg);
2126
open_rapdu_reader (int portno,
2127
const unsigned char *cookie, size_t length,
2128
int (*readfnc) (void *opaque,
2129
void *buffer, size_t size),
2130
void *readfnc_value,
2131
int (*writefnc) (void *opaque,
2132
const void *buffer, size_t size),
2133
void *writefnc_value,
2134
void (*closefnc) (void *opaque),
2135
void *closefnc_value)
2139
reader_table_t slotp;
2140
rapdu_msg_t msg = NULL;
2142
slot = new_reader_slot ();
2145
slotp = reader_table + slot;
2147
slotp->rapdu.handle = rapdu_new ();
2148
if (!slotp->rapdu.handle)
2155
rapdu_set_iofunc (slotp->rapdu.handle,
2156
readfnc, readfnc_value,
2157
writefnc, writefnc_value,
2158
closefnc, closefnc_value);
2159
rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2161
/* First try to get the current ATR, but if the card is inactive
2162
issue a reset instead. */
2163
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2164
if (err == RAPDU_STATUS_NEEDRESET)
2165
err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2168
log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2169
err < 0 ? strerror (errno): rapdu_strerror (err));
2172
err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2175
log_info ("receiving rapdu message failed: %s\n",
2176
err < 0 ? strerror (errno): rapdu_strerror (err));
2179
if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2181
log_info ("rapdu command GET ATR failed: %s\n",
2182
rapdu_strerror (msg->cmd));
2185
if (msg->datalen >= DIM (slotp->atr))
2187
log_error ("ATR returned by the RAPDU layer is too large\n");
2190
slotp->atrlen = msg->datalen;
2191
memcpy (slotp->atr, msg->data, msg->datalen);
2193
reader_table[slot].close_reader = close_rapdu_reader;
2194
reader_table[slot].reset_reader = reset_rapdu_reader;
2195
reader_table[slot].get_status_reader = my_rapdu_get_status;
2196
reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2197
reader_table[slot].dump_status_reader = NULL;
2199
dump_reader_status (slot);
2200
rapdu_msg_release (msg);
2204
rapdu_msg_release (msg);
2205
rapdu_release (slotp->rapdu.handle);
2210
#endif /*USE_G10CODE_RAPDU*/
2220
lock_slot (int slot)
2223
if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2225
log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2226
return SW_HOST_LOCKING_FAILED;
2228
#endif /*USE_GNU_PTH*/
2233
trylock_slot (int slot)
2236
if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2239
return SW_HOST_BUSY;
2240
log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2241
return SW_HOST_LOCKING_FAILED;
2243
#endif /*USE_GNU_PTH*/
2248
unlock_slot (int slot)
2251
if (!pth_mutex_release (&reader_table[slot].lock))
2252
log_error ("failed to release apdu lock: %s\n", strerror (errno));
2253
#endif /*USE_GNU_PTH*/
2257
/* Open the reader and return an internal slot number or -1 on
2258
error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2259
the first USB reader. For PC/SC the first listed reader). If
2260
OpenSC support is compiled in, we first try to use OpenSC. */
2262
apdu_open_reader (const char *portstr)
2264
static int pcsc_api_loaded, ct_api_loaded;
2267
if (!opt.disable_ccid)
2272
slot = open_ccid_reader (portstr);
2274
return slot; /* got one */
2276
/* If a CCID reader specification has been given, the user does
2277
not want a fallback to other drivers. */
2279
for (s=portstr, i=0; *s; s++)
2280
if (*s == ':' && (++i == 3))
2284
#endif /* HAVE_LIBUSB */
2287
if (!opt.disable_opensc)
2289
int port = portstr? atoi (portstr) : 0;
2291
return open_osc_reader (port);
2293
#endif /* HAVE_OPENSC */
2296
if (opt.ctapi_driver && *opt.ctapi_driver)
2298
int port = portstr? atoi (portstr) : 32768;
2304
handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2307
log_error ("apdu_open_reader: failed to open driver: %s\n",
2311
CT_init = dlsym (handle, "CT_init");
2312
CT_data = dlsym (handle, "CT_data");
2313
CT_close = dlsym (handle, "CT_close");
2314
if (!CT_init || !CT_data || !CT_close)
2316
log_error ("apdu_open_reader: invalid CT-API driver\n");
2322
return open_ct_reader (port);
2326
/* No ctAPI configured, so lets try the PC/SC API */
2327
if (!pcsc_api_loaded)
2329
#ifndef NEED_PCSC_WRAPPER
2332
handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2335
log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2336
opt.pcsc_driver, dlerror ());
2340
pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2341
pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2342
pcsc_list_readers = dlsym (handle, "SCardListReaders");
2344
if (!pcsc_list_readers)
2345
pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2347
pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2349
if (!pcsc_get_status_change)
2350
pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2352
pcsc_connect = dlsym (handle, "SCardConnect");
2355
pcsc_connect = dlsym (handle, "SCardConnectA");
2357
pcsc_reconnect = dlsym (handle, "SCardReconnect");
2359
if (!pcsc_reconnect)
2360
pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2362
pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2363
pcsc_status = dlsym (handle, "SCardStatus");
2366
pcsc_status = dlsym (handle, "SCardStatusA");
2368
pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2369
pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2370
pcsc_transmit = dlsym (handle, "SCardTransmit");
2371
pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2373
if (!pcsc_establish_context
2374
|| !pcsc_release_context
2375
|| !pcsc_list_readers
2376
|| !pcsc_get_status_change
2381
|| !pcsc_begin_transaction
2382
|| !pcsc_end_transaction
2384
/* || !pcsc_set_timeout */)
2386
/* Note that set_timeout is currently not used and also not
2387
available under Windows. */
2388
log_error ("apdu_open_reader: invalid PC/SC driver "
2389
"(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2390
!!pcsc_establish_context,
2391
!!pcsc_release_context,
2392
!!pcsc_list_readers,
2393
!!pcsc_get_status_change,
2398
!!pcsc_begin_transaction,
2399
!!pcsc_end_transaction,
2401
!!pcsc_set_timeout );
2405
#endif /*!NEED_PCSC_WRAPPER*/
2406
pcsc_api_loaded = 1;
2409
return open_pcsc_reader (portstr);
2413
/* Open an remote reader and return an internal slot number or -1 on
2414
error. This function is an alternative to apdu_open_reader and used
2415
with remote readers only. Note that the supplied CLOSEFNC will
2416
only be called once and the slot will not be valid afther this.
2418
If PORTSTR is NULL we default to the first availabe port.
2421
apdu_open_remote_reader (const char *portstr,
2422
const unsigned char *cookie, size_t length,
2423
int (*readfnc) (void *opaque,
2424
void *buffer, size_t size),
2425
void *readfnc_value,
2426
int (*writefnc) (void *opaque,
2427
const void *buffer, size_t size),
2428
void *writefnc_value,
2429
void (*closefnc) (void *opaque),
2430
void *closefnc_value)
2432
#ifdef USE_G10CODE_RAPDU
2433
return open_rapdu_reader (portstr? atoi (portstr) : 0,
2435
readfnc, readfnc_value,
2436
writefnc, writefnc_value,
2437
closefnc, closefnc_value);
2450
apdu_close_reader (int slot)
2452
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2453
return SW_HOST_NO_DRIVER;
2454
if (reader_table[slot].close_reader)
2455
return reader_table[slot].close_reader (slot);
2456
return SW_HOST_NOT_SUPPORTED;
2459
/* Shutdown a reader; that is basically the same as a close but keeps
2460
the handle ready for later use. A apdu_reset_header should be used
2461
to get it active again. */
2463
apdu_shutdown_reader (int slot)
2465
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2466
return SW_HOST_NO_DRIVER;
2467
if (reader_table[slot].shutdown_reader)
2468
return reader_table[slot].shutdown_reader (slot);
2469
return SW_HOST_NOT_SUPPORTED;
2472
/* Enumerate all readers and return information on whether this reader
2473
is in use. The caller should start with SLOT set to 0 and
2474
increment it with each call until an error is returned. */
2476
apdu_enum_reader (int slot, int *used)
2478
if (slot < 0 || slot >= MAX_READER)
2479
return SW_HOST_NO_DRIVER;
2480
*used = reader_table[slot].used;
2484
/* Do a reset for the card in reader at SLOT. */
2486
apdu_reset (int slot)
2490
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2491
return SW_HOST_NO_DRIVER;
2493
if ((sw = lock_slot (slot)))
2496
reader_table[slot].last_status = 0;
2497
if (reader_table[slot].reset_reader)
2498
sw = reader_table[slot].reset_reader (slot);
2502
/* If we got to here we know that a card is present
2503
and usable. Thus remember this. */
2504
reader_table[slot].last_status = (1|2|4| 0x8000);
2512
/* Activate a card if it has not yet been done. This is a kind of
2513
reset-if-required. It is useful to test for presence of a card
2514
before issuing a bunch of apdu commands. It does not wait on a
2517
apdu_activate (int slot)
2522
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2523
return SW_HOST_NO_DRIVER;
2525
if ((sw = trylock_slot (slot)))
2528
if (reader_table[slot].get_status_reader)
2529
sw = reader_table[slot].get_status_reader (slot, &s);
2533
if (!(s & 2)) /* Card not present. */
2534
sw = SW_HOST_NO_CARD;
2535
else if ( ((s & 2) && !(s & 4))
2536
|| !reader_table[slot].atrlen )
2538
/* We don't have an ATR or a card is present though inactive:
2540
if (reader_table[slot].reset_reader)
2542
reader_table[slot].last_status = 0;
2543
sw = reader_table[slot].reset_reader (slot);
2546
/* If we got to here we know that a card is present
2547
and usable. Thus remember this. */
2548
reader_table[slot].last_status = (1|2|4| 0x8000);
2561
apdu_get_atr (int slot, size_t *atrlen)
2565
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2568
buf = xtrymalloc (reader_table[slot].atrlen);
2571
memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2572
*atrlen = reader_table[slot].atrlen;
2578
/* Retrieve the status for SLOT. The function does only wait for the
2579
card to become available if HANG is set to true. On success the
2580
bits in STATUS will be set to
2582
bit 0 = card present and usable
2583
bit 1 = card present
2585
bit 3 = card access locked [not yet implemented]
2587
For must application, testing bit 0 is sufficient.
2589
CHANGED will receive the value of the counter tracking the number
2590
of card insertions. This value may be used to detect a card
2594
apdu_get_status (int slot, int hang,
2595
unsigned int *status, unsigned int *changed)
2600
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2601
return SW_HOST_NO_DRIVER;
2603
if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2606
if (reader_table[slot].get_status_reader)
2607
sw = reader_table[slot].get_status_reader (slot, &s);
2613
reader_table[slot].last_status = 0;
2617
/* Keep track of changes. We use one extra bit to test whether we
2618
have checked the status at least once. */
2619
if ( s != (reader_table[slot].last_status & 0x07ff)
2620
|| !reader_table[slot].last_status )
2622
reader_table[slot].change_counter++;
2623
/* Make sure that the ATR is invalid so that a reset will be by
2625
reader_table[slot].atrlen = 0;
2627
reader_table[slot].last_status = (s | 0x8000);
2632
*changed = reader_table[slot].change_counter;
2637
/* Dispatcher for the actual send_apdu function. Note, that this
2638
function should be called in locked state. */
2640
send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2641
unsigned char *buffer, size_t *buflen)
2643
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2644
return SW_HOST_NO_DRIVER;
2646
if (reader_table[slot].send_apdu_reader)
2647
return reader_table[slot].send_apdu_reader (slot,
2651
return SW_HOST_NOT_SUPPORTED;
2654
/* Send an APDU to the card in SLOT. The APDU is created from all
2655
given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2656
for LC won't sent this field and the data field; in this case DATA
2657
must also be passed as NULL. The return value is the status word
2658
or -1 for an invalid SLOT or other non card related error. If
2659
RETBUF is not NULL, it will receive an allocated buffer with the
2660
returned data. The length of that data will be put into
2661
*RETBUFLEN. The caller is reponsible for releasing the buffer even
2662
in case of errors. */
2664
apdu_send_le(int slot, int class, int ins, int p0, int p1,
2665
int lc, const char *data, int le,
2666
unsigned char **retbuf, size_t *retbuflen)
2668
#define RESULTLEN 256
2669
unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2672
unsigned char apdu[5+256+1];
2675
long rc; /* we need a long here due to PC/SC. */
2677
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2678
return SW_HOST_NO_DRIVER;
2681
log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
2682
class, ins, p0, p1, lc, le);
2684
if (lc != -1 && (lc > 255 || lc < 0))
2685
return SW_WRONG_LENGTH;
2686
if (le != -1 && (le > 256 || le < 1))
2687
return SW_WRONG_LENGTH;
2688
if ((!data && lc != -1) || (data && lc == -1))
2689
return SW_HOST_INV_VALUE;
2691
if ((sw = lock_slot (slot)))
2695
apdu[apdulen++] = class;
2696
apdu[apdulen++] = ins;
2697
apdu[apdulen++] = p0;
2698
apdu[apdulen++] = p1;
2701
apdu[apdulen++] = lc;
2702
memcpy (apdu+apdulen, data, lc);
2706
apdu[apdulen++] = le; /* Truncation is okay becuase 0 means 256. */
2707
assert (sizeof (apdu) >= apdulen);
2708
/* As safeguard don't pass any garbage from the stack to the driver. */
2709
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2710
resultlen = RESULTLEN;
2711
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2712
if (rc || resultlen < 2)
2714
log_error ("apdu_send_simple(%d) failed: %s\n",
2715
slot, apdu_strerror (rc));
2717
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2719
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2720
/* store away the returned data but strip the statusword. */
2724
log_debug (" response: sw=%04X datalen=%d\n", sw, resultlen);
2725
if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2726
log_printhex (" dump: ", result, resultlen);
2729
if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2733
*retbuf = xtrymalloc (resultlen? resultlen : 1);
2737
return SW_HOST_OUT_OF_CORE;
2739
*retbuflen = resultlen;
2740
memcpy (*retbuf, result, resultlen);
2743
else if ((sw & 0xff00) == SW_MORE_DATA)
2745
unsigned char *p = NULL, *tmp;
2746
size_t bufsize = 4096;
2748
/* It is likely that we need to return much more data, so we
2749
start off with a large buffer. */
2752
*retbuf = p = xtrymalloc (bufsize);
2756
return SW_HOST_OUT_OF_CORE;
2758
assert (resultlen < bufsize);
2759
memcpy (p, result, resultlen);
2765
int len = (sw & 0x00ff);
2768
log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2771
apdu[apdulen++] = class;
2772
apdu[apdulen++] = 0xC0;
2773
apdu[apdulen++] = 0;
2774
apdu[apdulen++] = 0;
2775
apdu[apdulen++] = len;
2776
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2777
resultlen = RESULTLEN;
2778
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2779
if (rc || resultlen < 2)
2781
log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2782
slot, apdu_strerror (rc));
2784
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2786
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2790
log_debug (" more: sw=%04X datalen=%d\n", sw, resultlen);
2791
if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2792
log_printhex (" dump: ", result, resultlen);
2795
if ((sw & 0xff00) == SW_MORE_DATA
2797
|| sw == SW_EOF_REACHED )
2799
if (retbuf && resultlen)
2801
if (p - *retbuf + resultlen > bufsize)
2803
bufsize += resultlen > 4096? resultlen: 4096;
2804
tmp = xtryrealloc (*retbuf, bufsize);
2808
return SW_HOST_OUT_OF_CORE;
2810
p = tmp + (p - *retbuf);
2813
memcpy (p, result, resultlen);
2818
log_info ("apdu_send_simple(%d) "
2819
"got unexpected status %04X from get response\n",
2822
while ((sw & 0xff00) == SW_MORE_DATA);
2826
*retbuflen = p - *retbuf;
2827
tmp = xtryrealloc (*retbuf, *retbuflen);
2835
if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2836
log_printhex (" dump: ", *retbuf, *retbuflen);
2842
/* Send an APDU to the card in SLOT. The APDU is created from all
2843
given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2844
LC won't sent this field and the data field; in this case DATA must
2845
also be passed as NULL. The return value is the status word or -1
2846
for an invalid SLOT or other non card related error. If RETBUF is
2847
not NULL, it will receive an allocated buffer with the returned
2848
data. The length of that data will be put into *RETBUFLEN. The
2849
caller is reponsible for releasing the buffer even in case of
2852
apdu_send (int slot, int class, int ins, int p0, int p1,
2853
int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2855
return apdu_send_le (slot, class, ins, p0, p1, lc, data, 256,
2859
/* Send an APDU to the card in SLOT. The APDU is created from all
2860
given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2861
LC won't sent this field and the data field; in this case DATA must
2862
also be passed as NULL. The return value is the status word or -1
2863
for an invalid SLOT or other non card related error. No data will be
2866
apdu_send_simple (int slot, int class, int ins, int p0, int p1,
2867
int lc, const char *data)
2869
return apdu_send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL);
2873
/* This is a more generic version of the apdu sending routine. It
2874
takes an already formatted APDU in APDUDATA or length APDUDATALEN
2875
and returns the with the APDU including the status word. With
2876
HANDLE_MORE set to true this function will handle the MORE DATA
2877
status and return all APDUs concatenated with one status word at
2878
the end. The function does not return a regular status word but 0
2879
on success. If the slot is locked, the fucntion returns
2882
apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
2884
unsigned char **retbuf, size_t *retbuflen)
2886
#define RESULTLEN 256
2887
unsigned char apdu[5+256+1];
2889
unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
2893
long rc; /* we need a long here due to PC/SC. */
2896
if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2897
return SW_HOST_NO_DRIVER;
2899
if ((sw = trylock_slot (slot)))
2902
/* We simply trucntate a too long APDU. */
2903
if (apdudatalen > sizeof apdu)
2904
apdudatalen = sizeof apdu;
2905
apdulen = apdudatalen;
2906
memcpy (apdu, apdudata, apdudatalen);
2907
class = apdulen? *apdu : 0;
2910
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2911
if (rc || resultlen < 2)
2913
log_error ("apdu_send_direct(%d) failed: %s\n",
2914
slot, apdu_strerror (rc));
2916
return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2918
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2919
/* Store away the returned data but strip the statusword. */
2923
log_debug (" response: sw=%04X datalen=%d\n", sw, resultlen);
2924
if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2925
log_printhex (" dump: ", result, resultlen);
2928
if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
2930
unsigned char *p = NULL, *tmp;
2931
size_t bufsize = 4096;
2933
/* It is likely that we need to return much more data, so we
2934
start off with a large buffer. */
2937
*retbuf = p = xtrymalloc (bufsize + 2);
2941
return SW_HOST_OUT_OF_CORE;
2943
assert (resultlen < bufsize);
2944
memcpy (p, result, resultlen);
2950
int len = (sw & 0x00ff);
2953
log_debug ("apdu_send_direct(%d): %d more bytes available\n",
2956
apdu[apdulen++] = class;
2957
apdu[apdulen++] = 0xC0;
2958
apdu[apdulen++] = 0;
2959
apdu[apdulen++] = 0;
2960
apdu[apdulen++] = len;
2961
memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
2962
resultlen = RESULTLEN;
2963
rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
2964
if (rc || resultlen < 2)
2966
log_error ("apdu_send_direct(%d) for get response failed: %s\n",
2967
slot, apdu_strerror (rc));
2969
return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2971
sw = (result[resultlen-2] << 8) | result[resultlen-1];
2975
log_debug (" more: sw=%04X datalen=%d\n", sw, 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);