~ubuntu-branches/ubuntu/jaunty/gnupg2/jaunty

« back to all changes in this revision

Viewing changes to g10/apdu.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* apdu.c - ISO 7816 APDU functions and low level I/O
 
2
 *      Copyright (C) 2003, 2004 Free Software Foundation, Inc.
 
3
 *
 
4
 * This file is part of GnuPG.
 
5
 *
 
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.
 
10
 *
 
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.
 
15
 *
 
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
 
19
 *
 
20
 * $Id: apdu.c,v 1.17 2004/10/28 09:06:50 wk Exp $
 
21
 */
 
22
 
 
23
#include <config.h>
 
24
#include <errno.h>
 
25
#include <stdio.h>
 
26
#include <stdlib.h>
 
27
#include <string.h>
 
28
#include <assert.h>
 
29
#include <signal.h>
 
30
#ifdef USE_GNU_PTH
 
31
# include <pth.h>
 
32
# include <unistd.h>
 
33
# include <fcntl.h>
 
34
#endif
 
35
#ifdef HAVE_OPENSC
 
36
# include <opensc/opensc.h>
 
37
# ifdef USE_GNU_PTH
 
38
# undef USE_GNU_PTH
 
39
# endif
 
40
#endif
 
41
 
 
42
/* If requested include the definitions for the remote APDU protocol
 
43
   code. */
 
44
#ifdef USE_G10CODE_RAPDU
 
45
#include "rapdu.h"
 
46
#endif /*USE_G10CODE_RAPDU*/
 
47
 
 
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
 
53
   there. */
 
54
#include "options.h"
 
55
#include "errors.h"
 
56
#include "memory.h"
 
57
#include "util.h"
 
58
#include "i18n.h"
 
59
#include "cardglue.h"
 
60
#else /* GNUPG_MAJOR_VERSION != 1 */
 
61
#include "scdaemon.h"
 
62
#endif /* GNUPG_MAJOR_VERSION != 1 */
 
63
 
 
64
#include "apdu.h"
 
65
#include "dynload.h"
 
66
#include "ccid-driver.h"
 
67
 
 
68
#ifdef USE_GNU_PTH
 
69
#define NEED_PCSC_WRAPPER 1
 
70
#endif
 
71
 
 
72
 
 
73
#define MAX_READER 4 /* Number of readers we support concurrently. */
 
74
 
 
75
 
 
76
#ifdef _WIN32
 
77
#define DLSTDCALL __stdcall
 
78
#else
 
79
#define DLSTDCALL
 
80
#endif
 
81
 
 
82
#ifdef _POSIX_OPEN_MAX
 
83
#define MAX_OPEN_FDS _POSIX_OPEN_MAX
 
84
#else
 
85
#define MAX_OPEN_FDS 20
 
86
#endif
 
87
 
 
88
 
 
89
/* A structure to collect information pertaining to one reader
 
90
   slot. */
 
91
struct reader_table_s {
 
92
  int used;            /* True if slot is used. */
 
93
  unsigned short port; /* Port number:  0 = unused, 1 - dev/tty */
 
94
 
 
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);
 
103
 
 
104
  struct {
 
105
    ccid_driver_t handle;
 
106
  } ccid;
 
107
  struct {
 
108
    unsigned long context;
 
109
    unsigned long card;
 
110
    unsigned long protocol;
 
111
#ifdef NEED_PCSC_WRAPPER
 
112
    int req_fd;
 
113
    int rsp_fd;
 
114
    pid_t pid;
 
115
#endif /*NEED_PCSC_WRAPPER*/
 
116
  } pcsc;
 
117
#ifdef HAVE_OPENSC
 
118
  struct {
 
119
    struct sc_context *ctx;
 
120
    struct sc_card *scard;
 
121
  } osc;
 
122
#endif /*HAVE_OPENSC*/
 
123
#ifdef USE_G10CODE_RAPDU
 
124
  struct {
 
125
    rapdu_t handle;
 
126
  } rapdu;
 
127
#endif /*USE_G10CODE_RAPDU*/
 
128
  char *rdrname;     /* Name of the connected reader or NULL if unknown. */
 
129
  int last_status;
 
130
  int status;
 
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
 
134
                              ready for use. */
 
135
  unsigned int change_counter;
 
136
#ifdef USE_GNU_PTH
 
137
  int lock_initialized;
 
138
  pth_mutex_t lock;
 
139
#endif
 
140
};
 
141
typedef struct reader_table_s *reader_table_t;
 
142
 
 
143
/* A global table to keep track of active readers. */
 
144
static struct reader_table_s reader_table[MAX_READER];
 
145
 
 
146
 
 
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,
 
152
                                   unsigned char *rsp);
 
153
static char (* DLSTDCALL CT_close) (unsigned short ctn);
 
154
 
 
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 
 
160
 
 
161
#define PCSC_PROTOCOL_T0     1 
 
162
#define PCSC_PROTOCOL_T1     2 
 
163
#define PCSC_PROTOCOL_RAW    4 
 
164
 
 
165
#define PCSC_SHARE_EXCLUSIVE 1
 
166
#define PCSC_SHARE_SHARED    2
 
167
#define PCSC_SHARE_DIRECT    3
 
168
 
 
169
#define PCSC_LEAVE_CARD      0
 
170
#define PCSC_RESET_CARD      1
 
171
#define PCSC_UNPOWER_CARD    2
 
172
#define PCSC_EJECT_CARD      3
 
173
 
 
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.  */
 
181
 
 
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.  */
 
193
 
 
194
 
 
195
struct pcsc_io_request_s 
 
196
{
 
197
  unsigned long protocol; 
 
198
  unsigned long pci_len;
 
199
};
 
200
 
 
201
typedef struct pcsc_io_request_s *pcsc_io_request_t;
 
202
 
 
203
struct pcsc_readerstate_s
 
204
{
 
205
  const char *reader;
 
206
  void *user_data;
 
207
  unsigned long current_state;
 
208
  unsigned long event_state;
 
209
  unsigned long atrlen;
 
210
  unsigned char atr[33];
 
211
};
 
212
 
 
213
typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
 
214
 
 
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,
 
221
                                      const char *groups,
 
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,
 
228
                                 const char *reader,
 
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);
 
256
 
 
257
 
 
258
 
 
259
 
 
260
/* 
 
261
      Helper
 
262
 */
 
263
 
 
264
 
 
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. */
 
267
static int 
 
268
new_reader_slot (void)    
 
269
{
 
270
  int i, reader = -1;
 
271
 
 
272
  for (i=0; i < MAX_READER; i++)
 
273
    {
 
274
      if (!reader_table[i].used && reader == -1)
 
275
        reader = i;
 
276
    }
 
277
  if (reader == -1)
 
278
    {
 
279
      log_error ("new_reader_slot: out of slots\n");
 
280
      return -1;
 
281
    }
 
282
#ifdef USE_GNU_PTH
 
283
  if (!reader_table[reader].lock_initialized)
 
284
    {
 
285
      if (!pth_mutex_init (&reader_table[reader].lock))
 
286
        {
 
287
          log_error ("error initializing mutex: %s\n", strerror (errno));
 
288
          return -1;
 
289
        }
 
290
      reader_table[reader].lock_initialized = 1;
 
291
    }
 
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;
 
299
 
 
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);
 
306
#endif
 
307
 
 
308
  return reader;
 
309
}
 
310
 
 
311
 
 
312
static void
 
313
dump_reader_status (int slot)
 
314
{
 
315
  if (!opt.verbose)
 
316
    return;
 
317
 
 
318
  if (reader_table[slot].dump_status_reader)
 
319
    reader_table[slot].dump_status_reader (slot);
 
320
 
 
321
  if (reader_table[slot].status != -1
 
322
      && reader_table[slot].atrlen)
 
323
    {
 
324
      log_info ("slot %d: ATR=", slot);
 
325
      log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
 
326
    }
 
327
}
 
328
 
 
329
 
 
330
 
 
331
static const char *
 
332
host_sw_string (long err)
 
333
{
 
334
  switch (err)
 
335
    {
 
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";
 
350
    }
 
351
}
 
352
 
 
353
 
 
354
const char *
 
355
apdu_strerror (int rc)
 
356
{
 
357
  switch (rc)
 
358
    {
 
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";
 
374
    default:
 
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";
 
380
    }
 
381
}
 
382
 
 
383
 
 
384
 
 
385
/* 
 
386
       ct API Interface 
 
387
 */
 
388
 
 
389
static const char *
 
390
ct_error_string (long err)
 
391
{
 
392
  switch (err)
 
393
    {
 
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";
 
401
    }
 
402
}
 
403
 
 
404
 
 
405
static void
 
406
ct_dump_reader_status (int slot)
 
407
{
 
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" :
 
411
            "ICC not present" );
 
412
}
 
413
 
 
414
 
 
415
/* Wait for the card in SLOT and activate it.  Return a status word
 
416
   error or 0 on success. */
 
417
static int
 
418
ct_activate_card (int slot)
 
419
{
 
420
  int rc;
 
421
  unsigned char dad[1], sad[1], cmd[11], buf[256];
 
422
  unsigned short buflen;
 
423
  
 
424
  /* Check whether card has been inserted. */
 
425
  dad[0] = 1;     /* Destination address: CT. */    
 
426
  sad[0] = 2;     /* Source address: Host. */
 
427
 
 
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. */
 
432
  cmd[4] = 0x00;
 
433
 
 
434
  buflen = DIM(buf);
 
435
 
 
436
  rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
 
437
  if (rc || buflen < 2 || buf[buflen-2] != 0x90)
 
438
    {
 
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;
 
442
    }
 
443
 
 
444
  /* Connected, now activate the card. */           
 
445
  dad[0] = 1;    /* Destination address: CT. */    
 
446
  sad[0] = 2;    /* Source address: Host. */
 
447
 
 
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. */
 
452
  cmd[4] = 0x00;
 
453
 
 
454
  buflen = DIM(buf);
 
455
 
 
456
  rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
 
457
  if (rc || buflen < 2 || buf[buflen-2] != 0x90)
 
458
    {
 
459
      log_error ("ct_activate_card(%d): activation failed: %s\n",
 
460
                 slot, ct_error_string (rc));
 
461
      if (!rc)
 
462
        log_printhex ("  received data:", buf, buflen);
 
463
      return SW_HOST_CARD_IO_ERROR;
 
464
    }
 
465
 
 
466
  /* Store the type and the ATR. */
 
467
  if (buflen - 2 > DIM (reader_table[0].atr))
 
468
    {
 
469
      log_error ("ct_activate_card(%d): ATR too long\n", slot);
 
470
      return SW_HOST_CARD_IO_ERROR;
 
471
    }
 
472
 
 
473
  reader_table[slot].status = buf[buflen - 1];
 
474
  memcpy (reader_table[slot].atr, buf, buflen - 2);
 
475
  reader_table[slot].atrlen = buflen - 2;
 
476
  return 0;
 
477
}
 
478
 
 
479
 
 
480
static int
 
481
close_ct_reader (int slot)
 
482
{
 
483
  CT_close (slot);
 
484
  reader_table[slot].used = 0;
 
485
  return 0;
 
486
}
 
487
 
 
488
static int
 
489
reset_ct_reader (int slot)
 
490
{
 
491
  /* FIXME: Check is this is sufficient do do a reset. */
 
492
  return ct_activate_card (slot);
 
493
}
 
494
 
 
495
 
 
496
static int
 
497
ct_get_status (int slot, unsigned int *status)
 
498
{
 
499
  *status = 1|2|4;  /* FIXME */
 
500
  return 0;
 
501
 
 
502
  return SW_HOST_NOT_SUPPORTED;
 
503
}
 
504
 
 
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. */
 
508
static int
 
509
ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
510
              unsigned char *buffer, size_t *buflen)
 
511
{
 
512
  int rc;
 
513
  unsigned char dad[1], sad[1];
 
514
  unsigned short ctbuflen;
 
515
  
 
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)))
 
519
    return rc;
 
520
 
 
521
  dad[0] = 0;     /* Destination address: Card. */    
 
522
  sad[0] = 2;     /* Source address: Host. */
 
523
  ctbuflen = *buflen;
 
524
  if (DBG_CARD_IO)
 
525
    log_printhex ("  CT_data:", apdu, apdulen);
 
526
  rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
 
527
  *buflen = ctbuflen;
 
528
 
 
529
  return rc? SW_HOST_CARD_IO_ERROR: 0;
 
530
}
 
531
 
 
532
 
 
533
 
 
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. */
 
537
static int
 
538
open_ct_reader (int port)
 
539
{
 
540
  int rc, reader;
 
541
 
 
542
  if (port < 0 || port > 0xffff)
 
543
    {
 
544
      log_error ("open_ct_reader: invalid port %d requested\n", port);
 
545
      return -1;
 
546
    }
 
547
  reader = new_reader_slot ();
 
548
  if (reader == -1)
 
549
    return reader;
 
550
  reader_table[reader].port = port;
 
551
 
 
552
  rc = CT_init (reader, (unsigned short)port);
 
553
  if (rc)
 
554
    {
 
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;
 
558
      return -1;
 
559
    }
 
560
 
 
561
  /* Only try to activate the card. */
 
562
  rc = ct_activate_card (reader);
 
563
  if (rc)
 
564
    {
 
565
      reader_table[reader].atrlen = 0;
 
566
      rc = 0;
 
567
    }
 
568
 
 
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;
 
574
 
 
575
  dump_reader_status (reader);
 
576
  return reader;
 
577
}
 
578
 
 
579
 
 
580
#ifdef NEED_PCSC_WRAPPER
 
581
static int
 
582
writen (int fd, const void *buf, size_t nbytes)
 
583
{
 
584
  size_t nleft = nbytes;
 
585
  int nwritten;
 
586
 
 
587
/*   log_printhex (" writen:", buf, nbytes); */
 
588
 
 
589
  while (nleft > 0)
 
590
    {
 
591
#ifdef USE_GNU_PTH
 
592
      nwritten = pth_write (fd, buf, nleft);
 
593
#else
 
594
      nwritten = write (fd, buf, nleft);
 
595
#endif
 
596
      if (nwritten < 0 && errno == EINTR)
 
597
        continue;
 
598
      if (nwritten < 0)
 
599
        return -1;
 
600
      nleft -= nwritten;
 
601
      buf = (const char*)buf + nwritten;
 
602
    }
 
603
  return 0;
 
604
}
 
605
 
 
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. */
 
608
static int
 
609
readn (int fd, void *buf, size_t buflen, size_t *nread)
 
610
{
 
611
  size_t nleft = buflen;
 
612
  int n;
 
613
/*   void *orig_buf = buf; */
 
614
 
 
615
  while (nleft > 0)
 
616
    {
 
617
#ifdef USE_GNU_PTH
 
618
      n = pth_read (fd, buf, nleft);
 
619
#else
 
620
      n = read (fd, buf, nleft);
 
621
#endif
 
622
      if (n < 0 && errno == EINTR) 
 
623
        continue;
 
624
      if (n < 0)
 
625
        return -1; /* read error. */
 
626
      if (!n)
 
627
        break; /* EOF */
 
628
      nleft -= n;
 
629
      buf = (char*)buf + n;
 
630
    }
 
631
  if (nread)
 
632
    *nread = buflen - nleft;
 
633
 
 
634
/*   log_printhex ("  readn:", orig_buf, *nread); */
 
635
    
 
636
  return 0;
 
637
}
 
638
#endif /*NEED_PCSC_WRAPPER*/
 
639
 
 
640
static const char *
 
641
pcsc_error_string (long err)
 
642
{
 
643
  const char *s;
 
644
 
 
645
  if (!err)
 
646
    return "okay";
 
647
  if ((err & 0x80100000) != 0x80100000)
 
648
    return "invalid PC/SC error code";
 
649
  err &= 0xffff;
 
650
  switch (err)
 
651
    {
 
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;
 
689
    }
 
690
  return s;
 
691
}
 
692
 
 
693
/* 
 
694
       PC/SC Interface
 
695
 */
 
696
 
 
697
static void
 
698
dump_pcsc_reader_status (int slot)
 
699
{
 
700
  log_info ("reader slot %d: active protocol:", slot);
 
701
  if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
 
702
    log_printf (" T0");
 
703
  else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
 
704
    log_printf (" T1");
 
705
  else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
 
706
    log_printf (" raw");
 
707
  log_printf ("\n");
 
708
}
 
709
 
 
710
 
 
711
static int
 
712
reset_pcsc_reader (int slot)
 
713
{
 
714
#ifdef NEED_PCSC_WRAPPER
 
715
  long err;
 
716
  reader_table_t slotp;
 
717
  size_t len;
 
718
  int i, n;
 
719
  unsigned char msgbuf[9];
 
720
 
 
721
  slotp = reader_table + slot;
 
722
 
 
723
  if (slotp->pcsc.req_fd == -1 
 
724
      || slotp->pcsc.rsp_fd == -1 
 
725
      || slotp->pcsc.pid == (pid_t)(-1) )
 
726
    {
 
727
      log_error ("pcsc_get_status: pcsc-wrapper not running\n");
 
728
      return SW_HOST_CARD_IO_ERROR;
 
729
    }
 
730
 
 
731
  msgbuf[0] = 0x05; /* RESET command. */
 
732
  len = 0;
 
733
  msgbuf[1] = (len >> 24);
 
734
  msgbuf[2] = (len >> 16);
 
735
  msgbuf[3] = (len >>  8);
 
736
  msgbuf[4] = (len      );
 
737
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
738
    {
 
739
      log_error ("error sending PC/SC RESET request: %s\n",
 
740
                 strerror (errno));
 
741
      goto command_failed;
 
742
    }
 
743
 
 
744
  /* Read the response. */
 
745
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
746
    {
 
747
      log_error ("error receiving PC/SC RESET response: %s\n",
 
748
                 i? strerror (errno) : "premature EOF");
 
749
      goto command_failed;
 
750
    }
 
751
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
752
  if (msgbuf[0] != 0x81 || len < 4)
 
753
    {
 
754
      log_error ("invalid response header from PC/SC received\n");
 
755
      goto command_failed;
 
756
    }
 
757
  len -= 4; /* Already read the error code. */
 
758
  if (len > DIM (slotp->atr))
 
759
    {
 
760
      log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
 
761
      goto command_failed;
 
762
    }
 
763
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
764
  if (err)
 
765
    {
 
766
      log_error ("PC/SC RESET failed: %s\n", pcsc_error_string (err));
 
767
      goto command_failed;
 
768
    }
 
769
 
 
770
  /* The open fucntion may return a zero for the ATR length to
 
771
     indicate that no card is present.  */
 
772
  n = len;
 
773
  if (n)
 
774
    {
 
775
      if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
 
776
        {
 
777
          log_error ("error receiving PC/SC RESET response: %s\n",
 
778
                     i? strerror (errno) : "premature EOF");
 
779
          goto command_failed;
 
780
        }
 
781
    }
 
782
  slotp->atrlen = len;
 
783
 
 
784
  return 0;
 
785
 
 
786
 command_failed:
 
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);
 
793
  slotp->used = 0;
 
794
  return -1;
 
795
 
 
796
#else /* !NEED_PCSC_WRAPPER */
 
797
  long err;
 
798
  char reader[250];
 
799
  unsigned long nreader, atrlen;
 
800
  unsigned long card_state, card_protocol;
 
801
 
 
802
  if (reader_table[slot].pcsc.card)
 
803
    {
 
804
      err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
 
805
      if (err)
 
806
        {
 
807
          log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
 
808
                     pcsc_error_string (err), err);
 
809
          return SW_HOST_CARD_IO_ERROR;
 
810
        }
 
811
      reader_table[slot].pcsc.card = 0;
 
812
    }
 
813
 
 
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);
 
820
  if (err)
 
821
    {
 
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;
 
826
    }      
 
827
 
 
828
  
 
829
  atrlen = 33;
 
830
  nreader = sizeof reader - 1;
 
831
  err = pcsc_status (reader_table[slot].pcsc.card,
 
832
                     reader, &nreader,
 
833
                     &card_state, &card_protocol,
 
834
                     reader_table[slot].atr, &atrlen);
 
835
  if (err)
 
836
    {
 
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;
 
841
    }
 
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;
 
845
 
 
846
  return 0;
 
847
#endif /* !NEED_PCSC_WRAPPER */
 
848
}
 
849
 
 
850
 
 
851
static int
 
852
pcsc_get_status (int slot, unsigned int *status)
 
853
{
 
854
#ifdef NEED_PCSC_WRAPPER
 
855
  long err;
 
856
  reader_table_t slotp;
 
857
  size_t len, full_len;
 
858
  int i, n;
 
859
  unsigned char msgbuf[9];
 
860
  unsigned char buffer[12];
 
861
 
 
862
  slotp = reader_table + slot;
 
863
 
 
864
  if (slotp->pcsc.req_fd == -1 
 
865
      || slotp->pcsc.rsp_fd == -1 
 
866
      || slotp->pcsc.pid == (pid_t)(-1) )
 
867
    {
 
868
      log_error ("pcsc_get_status: pcsc-wrapper not running\n");
 
869
      return SW_HOST_CARD_IO_ERROR;
 
870
    }
 
871
 
 
872
  msgbuf[0] = 0x04; /* STATUS command. */
 
873
  len = 0;
 
874
  msgbuf[1] = (len >> 24);
 
875
  msgbuf[2] = (len >> 16);
 
876
  msgbuf[3] = (len >>  8);
 
877
  msgbuf[4] = (len      );
 
878
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
879
    {
 
880
      log_error ("error sending PC/SC STATUS request: %s\n",
 
881
                 strerror (errno));
 
882
      goto command_failed;
 
883
    }
 
884
 
 
885
  /* Read the response. */
 
886
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
887
    {
 
888
      log_error ("error receiving PC/SC STATUS response: %s\n",
 
889
                 i? strerror (errno) : "premature EOF");
 
890
      goto command_failed;
 
891
    }
 
892
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
893
  if (msgbuf[0] != 0x81 || len < 4)
 
894
    {
 
895
      log_error ("invalid response header from PC/SC received\n");
 
896
      goto command_failed;
 
897
    }
 
898
  len -= 4; /* Already read the error code. */
 
899
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
900
  if (err)
 
901
    {
 
902
      log_error ("pcsc_status failed: %s (0x%lx)\n",
 
903
                 pcsc_error_string (err), err);
 
904
      return SW_HOST_CARD_IO_ERROR;
 
905
    }
 
906
 
 
907
  full_len = len;
 
908
  
 
909
  n = 8 < len ? 8 : len;
 
910
  if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != 8)
 
911
    {
 
912
      log_error ("error receiving PC/SC STATUS response: %s\n",
 
913
                 i? strerror (errno) : "premature EOF");
 
914
      goto command_failed;
 
915
    }
 
916
 
 
917
  full_len -= len;
 
918
  /* Newer versions of the wrapper might send more status bytes.
 
919
     Read them. */
 
920
  while (full_len)
 
921
    {
 
922
      unsigned char dummybuf[128];
 
923
 
 
924
      n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
 
925
      if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
 
926
        {
 
927
          log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
928
                     i? strerror (errno) : "premature EOF");
 
929
          goto command_failed;
 
930
        }
 
931
      full_len -= n;
 
932
    }
 
933
   
 
934
  /* We are lucky: The wrapper already returns the data in the
 
935
     required format. */
 
936
  *status = buffer[3];
 
937
 
 
938
  return 0;
 
939
 
 
940
 command_failed:
 
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);
 
947
  slotp->used = 0;
 
948
  return -1;
 
949
 
 
950
#else /*!NEED_PCSC_WRAPPER*/
 
951
 
 
952
  long err;
 
953
  struct pcsc_readerstate_s rdrstates[1];
 
954
  
 
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,
 
959
                                0,
 
960
                                rdrstates, 1);
 
961
  if (err == 0x8010000a) /* Timeout.  */
 
962
    err = 0;
 
963
  if (err)
 
964
    {
 
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;
 
968
    }
 
969
 
 
970
 
 
971
  /*   log_debug  */
 
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":"" ); */
 
983
 
 
984
  *status = 0;
 
985
  if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
 
986
    *status |= 2;
 
987
  if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
 
988
    *status |= 4;
 
989
  /* We indicate a useful card if it is not in use by another
 
990
     application.  This is because we only use exclusive access
 
991
     mode.  */
 
992
  if ( (*status & 6) == 6
 
993
       && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
 
994
    *status |= 1;
 
995
  
 
996
  return 0; 
 
997
#endif /*!NEED_PCSC_WRAPPER*/
 
998
}
 
999
 
 
1000
 
 
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. */
 
1004
static int
 
1005
pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
1006
                unsigned char *buffer, size_t *buflen)
 
1007
{
 
1008
#ifdef NEED_PCSC_WRAPPER
 
1009
  long err;
 
1010
  reader_table_t slotp;
 
1011
  size_t len, full_len;
 
1012
  int i, n;
 
1013
  unsigned char msgbuf[9];
 
1014
 
 
1015
  if (!reader_table[slot].atrlen
 
1016
      && (err = reset_pcsc_reader (slot)))
 
1017
    return err;
 
1018
 
 
1019
  if (DBG_CARD_IO)
 
1020
    log_printhex ("  PCSC_data:", apdu, apdulen);
 
1021
 
 
1022
  slotp = reader_table + slot;
 
1023
 
 
1024
  if (slotp->pcsc.req_fd == -1 
 
1025
      || slotp->pcsc.rsp_fd == -1 
 
1026
      || slotp->pcsc.pid == (pid_t)(-1) )
 
1027
    {
 
1028
      log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
 
1029
      return SW_HOST_CARD_IO_ERROR;
 
1030
    }
 
1031
 
 
1032
  msgbuf[0] = 0x03; /* TRANSMIT command. */
 
1033
  len = apdulen;
 
1034
  msgbuf[1] = (len >> 24);
 
1035
  msgbuf[2] = (len >> 16);
 
1036
  msgbuf[3] = (len >>  8);
 
1037
  msgbuf[4] = (len      );
 
1038
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
 
1039
       || writen (slotp->pcsc.req_fd, apdu, len))
 
1040
    {
 
1041
      log_error ("error sending PC/SC TRANSMIT request: %s\n",
 
1042
                 strerror (errno));
 
1043
      goto command_failed;
 
1044
    }
 
1045
 
 
1046
  /* Read the response. */
 
1047
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1048
    {
 
1049
      log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1050
                 i? strerror (errno) : "premature EOF");
 
1051
      goto command_failed;
 
1052
    }
 
1053
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1054
  if (msgbuf[0] != 0x81 || len < 4)
 
1055
    {
 
1056
      log_error ("invalid response header from PC/SC received\n");
 
1057
      goto command_failed;
 
1058
    }
 
1059
  len -= 4; /* Already read the error code. */
 
1060
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1061
  if (err)
 
1062
    {
 
1063
      log_error ("pcsc_transmit failed: %s (0x%lx)\n",
 
1064
                 pcsc_error_string (err), err);
 
1065
      return SW_HOST_CARD_IO_ERROR;
 
1066
    }
 
1067
 
 
1068
   full_len = len;
 
1069
   
 
1070
   n = *buflen < len ? *buflen : len;
 
1071
   if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
 
1072
     {
 
1073
       log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1074
                  i? strerror (errno) : "premature EOF");
 
1075
       goto command_failed;
 
1076
     }
 
1077
   *buflen = n;
 
1078
 
 
1079
   full_len -= len;
 
1080
   if (full_len)
 
1081
     {
 
1082
       log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
 
1083
       err = SW_HOST_INV_VALUE;
 
1084
     }
 
1085
   /* We need to read any rest of the response, to keep the
 
1086
      protocol runnng. */
 
1087
   while (full_len)
 
1088
     {
 
1089
       unsigned char dummybuf[128];
 
1090
 
 
1091
       n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
 
1092
       if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
 
1093
         {
 
1094
           log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1095
                      i? strerror (errno) : "premature EOF");
 
1096
           goto command_failed;
 
1097
         }
 
1098
       full_len -= n;
 
1099
     }
 
1100
 
 
1101
   return err;
 
1102
 
 
1103
 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);
 
1110
  slotp->used = 0;
 
1111
  return -1;
 
1112
 
 
1113
#else /*!NEED_PCSC_WRAPPER*/
 
1114
 
 
1115
  long err;
 
1116
  struct pcsc_io_request_s send_pci;
 
1117
  unsigned long recv_len;
 
1118
  
 
1119
  if (!reader_table[slot].atrlen
 
1120
      && (err = reset_pcsc_reader (slot)))
 
1121
    return err;
 
1122
 
 
1123
  if (DBG_CARD_IO)
 
1124
    log_printhex ("  PCSC_data:", apdu, apdulen);
 
1125
 
 
1126
  if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
 
1127
      send_pci.protocol = PCSC_PROTOCOL_T1;
 
1128
  else
 
1129
      send_pci.protocol = PCSC_PROTOCOL_T0;
 
1130
  send_pci.pci_len = sizeof send_pci;
 
1131
  recv_len = *buflen;
 
1132
  err = pcsc_transmit (reader_table[slot].pcsc.card,
 
1133
                       &send_pci, apdu, apdulen,
 
1134
                       NULL, buffer, &recv_len);
 
1135
  *buflen = recv_len;
 
1136
  if (err)
 
1137
    log_error ("pcsc_transmit failed: %s (0x%lx)\n",
 
1138
               pcsc_error_string (err), err);
 
1139
  
 
1140
  return err? SW_HOST_CARD_IO_ERROR:0; 
 
1141
#endif /*!NEED_PCSC_WRAPPER*/
 
1142
}
 
1143
 
 
1144
 
 
1145
static int
 
1146
close_pcsc_reader (int slot)
 
1147
{
 
1148
#ifdef NEED_PCSC_WRAPPER
 
1149
  long err;
 
1150
  reader_table_t slotp;
 
1151
  size_t len;
 
1152
  int i;
 
1153
  unsigned char msgbuf[9];
 
1154
 
 
1155
  slotp = reader_table + slot;
 
1156
 
 
1157
  if (slotp->pcsc.req_fd == -1 
 
1158
      || slotp->pcsc.rsp_fd == -1 
 
1159
      || slotp->pcsc.pid == (pid_t)(-1) )
 
1160
    {
 
1161
      log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
 
1162
      return 0;
 
1163
    }
 
1164
 
 
1165
  msgbuf[0] = 0x02; /* CLOSE command. */
 
1166
  len = 0;
 
1167
  msgbuf[1] = (len >> 24);
 
1168
  msgbuf[2] = (len >> 16);
 
1169
  msgbuf[3] = (len >>  8);
 
1170
  msgbuf[4] = (len      );
 
1171
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
1172
    {
 
1173
      log_error ("error sending PC/SC CLOSE request: %s\n",
 
1174
                 strerror (errno));
 
1175
      goto command_failed;
 
1176
    }
 
1177
 
 
1178
  /* Read the response. */
 
1179
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1180
    {
 
1181
      log_error ("error receiving PC/SC CLOSE response: %s\n",
 
1182
                 i? strerror (errno) : "premature EOF");
 
1183
      goto command_failed;
 
1184
    }
 
1185
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1186
  if (msgbuf[0] != 0x81 || len < 4)
 
1187
    {
 
1188
      log_error ("invalid response header from PC/SC received\n");
 
1189
      goto command_failed;
 
1190
    }
 
1191
  len -= 4; /* Already read the error code. */
 
1192
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1193
  if (err)
 
1194
    log_error ("pcsc_close failed: %s (0x%lx)\n",
 
1195
               pcsc_error_string (err), err);
 
1196
  
 
1197
  /* We will the wrapper in any case - errors are merely
 
1198
     informational. */
 
1199
  
 
1200
 command_failed:
 
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);
 
1207
  slotp->used = 0;
 
1208
  return 0;
 
1209
 
 
1210
#else /*!NEED_PCSC_WRAPPER*/
 
1211
 
 
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;
 
1216
  return 0;
 
1217
#endif /*!NEED_PCSC_WRAPPER*/
 
1218
}
 
1219
 
 
1220
static int
 
1221
open_pcsc_reader (const char *portstr)
 
1222
{
 
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
 
1226
   of libpcsclite. */
 
1227
  int slot;
 
1228
  reader_table_t slotp;
 
1229
  int fd, rp[2], wp[2];
 
1230
  int n, i;
 
1231
  pid_t pid;
 
1232
  size_t len;
 
1233
  unsigned char msgbuf[9];
 
1234
  int err;
 
1235
 
 
1236
  slot = new_reader_slot ();
 
1237
  if (slot == -1)
 
1238
    return -1;
 
1239
  slotp = reader_table + slot;
 
1240
 
 
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. */
 
1244
  
 
1245
  if (pipe (rp) == -1)
 
1246
    {
 
1247
      log_error ("error creating a pipe: %s\n", strerror (errno));
 
1248
      slotp->used = 0;
 
1249
      return -1;
 
1250
    }
 
1251
  if (pipe (wp) == -1)
 
1252
    {
 
1253
      log_error ("error creating a pipe: %s\n", strerror (errno));
 
1254
      close (rp[0]);
 
1255
      close (rp[1]);
 
1256
      slotp->used = 0;
 
1257
      return -1;
 
1258
    }
 
1259
      
 
1260
  pid = fork ();
 
1261
  if (pid == -1)
 
1262
    {
 
1263
      log_error ("error forking process: %s\n", strerror (errno));
 
1264
      close (rp[0]);
 
1265
      close (rp[1]);
 
1266
      close (wp[0]);
 
1267
      close (wp[1]);
 
1268
      slotp->used = 0;
 
1269
      return -1;
 
1270
    }
 
1271
  slotp->pcsc.pid = pid;
 
1272
 
 
1273
  if (!pid)
 
1274
    { /*
 
1275
         === Child ===
 
1276
       */
 
1277
 
 
1278
      /* Double fork. */
 
1279
      pid = fork ();
 
1280
      if (pid == -1)
 
1281
        _exit (31); 
 
1282
      if (pid)
 
1283
        _exit (0); /* Immediate exit this parent, so that the child
 
1284
                      gets cleaned up by the init process. */
 
1285
 
 
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));
 
1291
      
 
1292
      /* Send stderr to the bit bucket. */
 
1293
      fd = open ("/dev/null", O_WRONLY);
 
1294
      if (fd == -1)
 
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));
 
1298
 
 
1299
      /* Close all other files. */
 
1300
      n = sysconf (_SC_OPEN_MAX);
 
1301
      if (n < 0)
 
1302
        n = MAX_OPEN_FDS;
 
1303
      for (i=3; i < n; i++)
 
1304
        close(i);
 
1305
      errno = 0;
 
1306
 
 
1307
      execl (GNUPG_LIBDIR "/pcsc-wrapper",
 
1308
             "pcsc-wrapper",
 
1309
             "--",
 
1310
             "1", /* API version */
 
1311
             opt.pcsc_driver, /* Name of the PC/SC library. */
 
1312
              NULL);
 
1313
      _exit (31);
 
1314
    }
 
1315
 
 
1316
  /* 
 
1317
     === Parent ===
 
1318
   */
 
1319
  close (wp[0]);
 
1320
  close (rp[1]);
 
1321
  slotp->pcsc.req_fd = wp[1];
 
1322
  slotp->pcsc.rsp_fd = rp[0];
 
1323
 
 
1324
  /* Wait for the intermediate child to terminate. */
 
1325
#ifdef USE_GNU_PTH
 
1326
#define WAIT pth_waitpid 
 
1327
#else
 
1328
#define WAIT waitpid 
 
1329
#endif
 
1330
  while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
 
1331
    ;
 
1332
#undef X
 
1333
 
 
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);
 
1340
  msgbuf[4] = (len      );
 
1341
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
 
1342
       || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
 
1343
    {
 
1344
      log_error ("error sending PC/SC OPEN request: %s\n",
 
1345
                 strerror (errno));
 
1346
      goto command_failed;
 
1347
    }
 
1348
  /* Read the response. */
 
1349
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1350
    {
 
1351
      log_error ("error receiving PC/SC OPEN response: %s\n",
 
1352
                 i? strerror (errno) : "premature EOF");
 
1353
      goto command_failed;
 
1354
    }
 
1355
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1356
  if (msgbuf[0] != 0x81 || len < 4)
 
1357
    {
 
1358
      log_error ("invalid response header from PC/SC received\n");
 
1359
      goto command_failed;
 
1360
    }
 
1361
  len -= 4; /* Already read the error code. */
 
1362
  if (len > DIM (slotp->atr))
 
1363
    {
 
1364
      log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
 
1365
      goto command_failed;
 
1366
    }
 
1367
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1368
  if (err)
 
1369
    {
 
1370
      log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
 
1371
      goto command_failed;
 
1372
    }
 
1373
 
 
1374
  slotp->last_status = 0;
 
1375
 
 
1376
  /* The open fucntion may return a zero for the ATR length to
 
1377
     indicate that no card is present.  */
 
1378
  n = len;
 
1379
  if (n)
 
1380
    {
 
1381
      if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
 
1382
        {
 
1383
          log_error ("error receiving PC/SC OPEN response: %s\n",
 
1384
                     i? strerror (errno) : "premature EOF");
 
1385
          goto command_failed;
 
1386
        }
 
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);
 
1390
    }
 
1391
  slotp->atrlen = len;
 
1392
 
 
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;
 
1398
 
 
1399
  dump_reader_status (slot); 
 
1400
  return slot;
 
1401
 
 
1402
 command_failed:
 
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);
 
1409
  slotp->used = 0;
 
1410
  return -1;
 
1411
#else /*!NEED_PCSC_WRAPPER */
 
1412
  long err;
 
1413
  int slot;
 
1414
  char *list = NULL;
 
1415
  unsigned long nreader, listlen, atrlen;
 
1416
  char *p;
 
1417
  unsigned long card_state, card_protocol;
 
1418
 
 
1419
  slot = new_reader_slot ();
 
1420
  if (slot == -1)
 
1421
    return -1;
 
1422
 
 
1423
  err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
 
1424
                                &reader_table[slot].pcsc.context);
 
1425
  if (err)
 
1426
    {
 
1427
      log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
 
1428
                 pcsc_error_string (err), err);
 
1429
      reader_table[slot].used = 0;
 
1430
      return -1;
 
1431
    }
 
1432
  
 
1433
  err = pcsc_list_readers (reader_table[slot].pcsc.context,
 
1434
                           NULL, NULL, &nreader);
 
1435
  if (!err)
 
1436
    {
 
1437
      list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
 
1438
      if (!list)
 
1439
        {
 
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;
 
1443
          return -1;
 
1444
        }
 
1445
      err = pcsc_list_readers (reader_table[slot].pcsc.context,
 
1446
                               NULL, list, &nreader);
 
1447
    }
 
1448
  if (err)
 
1449
    {
 
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;
 
1454
      xfree (list);
 
1455
      return -1;
 
1456
    }
 
1457
 
 
1458
  listlen = nreader;
 
1459
  p = list;
 
1460
  while (nreader)
 
1461
    {
 
1462
      if (!*p && !p[1])
 
1463
        break;
 
1464
      if (*p)
 
1465
        log_info ("detected reader `%s'\n", p);
 
1466
      if (nreader < (strlen (p)+1))
 
1467
        {
 
1468
          log_error ("invalid response from pcsc_list_readers\n");
 
1469
          break;
 
1470
        }
 
1471
      nreader -= strlen (p)+1;
 
1472
      p += strlen (p) + 1;
 
1473
    }
 
1474
 
 
1475
  reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
 
1476
  if (!reader_table[slot].rdrname)
 
1477
    {
 
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;
 
1481
      return -1;
 
1482
    }
 
1483
  strcpy (reader_table[slot].rdrname, portstr? portstr : list);
 
1484
  xfree (list);
 
1485
  list = NULL;
 
1486
 
 
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;
 
1495
  else if (err)
 
1496
    {
 
1497
      log_error ("pcsc_connect failed: %s (0x%lx)\n",
 
1498
                  pcsc_error_string (err), err);
 
1499
  
 
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;
 
1504
      return -1;
 
1505
    }      
 
1506
 
 
1507
  reader_table[slot].atrlen = 0;
 
1508
  reader_table[slot].last_status = 0;
 
1509
  if (!err)
 
1510
    {
 
1511
      char reader[250];
 
1512
      unsigned long readerlen;
 
1513
 
 
1514
      atrlen = 32;
 
1515
      readerlen = sizeof reader -1 ;
 
1516
      err = pcsc_status (reader_table[slot].pcsc.card,
 
1517
                         reader, &readerlen,
 
1518
                         &card_state, &card_protocol,
 
1519
                         reader_table[slot].atr, &atrlen);
 
1520
      if (err)
 
1521
        log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
 
1522
                   pcsc_error_string (err), err, readerlen);
 
1523
      else
 
1524
        {
 
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);
 
1531
        }
 
1532
    }
 
1533
 
 
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;
 
1539
 
 
1540
/*   log_debug ("state    from pcsc_status: 0x%lx\n", card_state); */
 
1541
/*   log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
 
1542
 
 
1543
  dump_reader_status (slot); 
 
1544
  return slot;
 
1545
#endif /*!NEED_PCSC_WRAPPER */
 
1546
}
 
1547
 
 
1548
 
 
1549
 
 
1550
 
 
1551
#ifdef HAVE_LIBUSB
 
1552
/* 
 
1553
     Internal CCID driver interface.
 
1554
 */
 
1555
 
 
1556
 
 
1557
static void
 
1558
dump_ccid_reader_status (int slot)
 
1559
{
 
1560
  log_info ("reader slot %d: using ccid driver\n", slot);
 
1561
}
 
1562
 
 
1563
static int
 
1564
close_ccid_reader (int slot)
 
1565
{
 
1566
  ccid_close_reader (reader_table[slot].ccid.handle);
 
1567
  reader_table[slot].used = 0;
 
1568
  return 0;
 
1569
}                       
 
1570
  
 
1571
 
 
1572
static int
 
1573
shutdown_ccid_reader (int slot)
 
1574
{
 
1575
  ccid_shutdown_reader (reader_table[slot].ccid.handle);
 
1576
  return 0;
 
1577
}                       
 
1578
  
 
1579
 
 
1580
static int
 
1581
reset_ccid_reader (int slot)
 
1582
{
 
1583
  int err;
 
1584
  reader_table_t slotp = reader_table + slot;
 
1585
  unsigned char atr[33];
 
1586
  size_t atrlen;
 
1587
 
 
1588
  err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
 
1589
  if (err)
 
1590
    return err;
 
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); 
 
1596
  return 0;
 
1597
}                       
 
1598
  
 
1599
 
 
1600
static int
 
1601
get_status_ccid (int slot, unsigned int *status)
 
1602
{
 
1603
  int rc;
 
1604
  int bits;
 
1605
 
 
1606
  rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
 
1607
  if (rc)
 
1608
    return -1;
 
1609
 
 
1610
  if (bits == 0)
 
1611
    *status = 1|2|4;
 
1612
  else if (bits == 1)
 
1613
    *status = 2;
 
1614
  else 
 
1615
    *status = 0;
 
1616
 
 
1617
  return 0;
 
1618
}
 
1619
 
 
1620
 
 
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. */
 
1624
static int
 
1625
send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
 
1626
                unsigned char *buffer, size_t *buflen)
 
1627
{
 
1628
  long err;
 
1629
  size_t maxbuflen;
 
1630
 
 
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)))
 
1634
    return err;
 
1635
 
 
1636
  if (DBG_CARD_IO)
 
1637
    log_printhex ("  APDU_data:", apdu, apdulen);
 
1638
 
 
1639
  maxbuflen = *buflen;
 
1640
  err = ccid_transceive (reader_table[slot].ccid.handle,
 
1641
                         apdu, apdulen,
 
1642
                         buffer, maxbuflen, buflen);
 
1643
  if (err)
 
1644
    log_error ("ccid_transceive failed: (0x%lx)\n",
 
1645
               err);
 
1646
  
 
1647
  return err; 
 
1648
}
 
1649
 
 
1650
/* Open the reader and try to read an ATR.  */
 
1651
static int
 
1652
open_ccid_reader (const char *portstr)
 
1653
{
 
1654
  int err;
 
1655
  int slot;
 
1656
  reader_table_t slotp;
 
1657
 
 
1658
  slot = new_reader_slot ();
 
1659
  if (slot == -1)
 
1660
    return -1;
 
1661
  slotp = reader_table + slot;
 
1662
 
 
1663
  err = ccid_open_reader (&slotp->ccid.handle, portstr);
 
1664
  if (err)
 
1665
    {
 
1666
      slotp->used = 0;
 
1667
      return -1;
 
1668
    }
 
1669
 
 
1670
  err = ccid_get_atr (slotp->ccid.handle,
 
1671
                      slotp->atr, sizeof slotp->atr, &slotp->atrlen);
 
1672
  if (err)
 
1673
    {
 
1674
      slotp->atrlen = 0;
 
1675
      err = 0;
 
1676
    }
 
1677
  else
 
1678
    {
 
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);
 
1682
    }
 
1683
 
 
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;
 
1690
 
 
1691
  dump_reader_status (slot); 
 
1692
  return slot;
 
1693
}
 
1694
 
 
1695
 
 
1696
 
 
1697
#endif /* HAVE_LIBUSB */
 
1698
 
 
1699
 
 
1700
 
 
1701
#ifdef HAVE_OPENSC
 
1702
/* 
 
1703
     OpenSC Interface.
 
1704
 
 
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.
 
1708
 */
 
1709
 
 
1710
 
 
1711
static int
 
1712
close_osc_reader (int slot)
 
1713
{
 
1714
  /* FIXME: Implement. */
 
1715
  reader_table[slot].used = 0;
 
1716
  return 0;
 
1717
}
 
1718
 
 
1719
static int
 
1720
reset_osc_reader (int slot)
 
1721
{
 
1722
  return SW_HOST_NOT_SUPPORTED;
 
1723
}
 
1724
 
 
1725
 
 
1726
static int
 
1727
osc_get_status (int slot, unsigned int *status)
 
1728
{
 
1729
  return SW_HOST_NOT_SUPPORTED;
 
1730
}
 
1731
 
 
1732
 
 
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. */
 
1736
static int
 
1737
osc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
1738
                unsigned char *buffer, size_t *buflen)
 
1739
{
 
1740
  long err;
 
1741
  struct sc_apdu a;
 
1742
  unsigned char data[SC_MAX_APDU_BUFFER_SIZE];
 
1743
  unsigned char result[SC_MAX_APDU_BUFFER_SIZE];
 
1744
 
 
1745
  if (DBG_CARD_IO)
 
1746
    log_printhex ("  APDU_data:", apdu, apdulen);
 
1747
 
 
1748
  if (apdulen < 4)
 
1749
    {
 
1750
      log_error ("osc_send_apdu: APDU is too short\n");
 
1751
      return SW_HOST_INV_VALUE;
 
1752
    }
 
1753
 
 
1754
  memset(&a, 0, sizeof a);
 
1755
  a.cla = *apdu++;
 
1756
  a.ins = *apdu++;
 
1757
  a.p1 = *apdu++;
 
1758
  a.p2 = *apdu++;
 
1759
  apdulen -= 4;
 
1760
 
 
1761
  if (!apdulen)
 
1762
    a.cse = SC_APDU_CASE_1;
 
1763
  else if (apdulen == 1) 
 
1764
    {
 
1765
      a.le = *apdu? *apdu : 256;
 
1766
      apdu++; apdulen--;
 
1767
      a.cse = SC_APDU_CASE_2_SHORT;
 
1768
    }
 
1769
  else
 
1770
    {
 
1771
      a.lc = *apdu++; apdulen--;
 
1772
      if (apdulen < a.lc)
 
1773
        {
 
1774
          log_error ("osc_send_apdu: APDU shorter than specified in Lc\n");
 
1775
          return SW_HOST_INV_VALUE;
 
1776
 
 
1777
        }
 
1778
      memcpy(data, apdu, a.lc);
 
1779
      apdu += a.lc; apdulen -= a.lc;
 
1780
 
 
1781
      a.data = data;
 
1782
      a.datalen = a.lc;
 
1783
      
 
1784
      if (!apdulen)
 
1785
        a.cse = SC_APDU_CASE_3_SHORT;
 
1786
      else
 
1787
        {
 
1788
          a.le = *apdu? *apdu : 256;
 
1789
          apdu++; apdulen--;
 
1790
          if (apdulen)
 
1791
            {
 
1792
              log_error ("osc_send_apdu: APDU larger than specified\n");
 
1793
              return SW_HOST_INV_VALUE;
 
1794
            }
 
1795
          a.cse = SC_APDU_CASE_4_SHORT;
 
1796
        }
 
1797
    }
 
1798
 
 
1799
  a.resp = result;
 
1800
  a.resplen = DIM(result);
 
1801
 
 
1802
  err = sc_transmit_apdu (reader_table[slot].osc.scard, &a);
 
1803
  if (err)
 
1804
    {
 
1805
      log_error ("sc_apdu_transmit failed: %s\n", sc_strerror (err));
 
1806
      return SW_HOST_CARD_IO_ERROR;
 
1807
    }
 
1808
 
 
1809
  if (*buflen < 2 || a.resplen > *buflen - 2)
 
1810
    {
 
1811
      log_error ("osc_send_apdu: provided buffer too short to store result\n");
 
1812
      return SW_HOST_INV_VALUE;
 
1813
    }
 
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;
 
1818
  return 0;
 
1819
}
 
1820
 
 
1821
static int
 
1822
open_osc_reader (int portno)
 
1823
{
 
1824
  int err;
 
1825
  int slot;
 
1826
  reader_table_t slotp;
 
1827
 
 
1828
  slot = new_reader_slot ();
 
1829
  if (slot == -1)
 
1830
    return -1;
 
1831
  slotp = reader_table + slot;
 
1832
 
 
1833
  err = sc_establish_context (&slotp->osc.ctx, "scdaemon");
 
1834
  if (err)
 
1835
    {
 
1836
      log_error ("failed to establish SC context: %s\n", sc_strerror (err));
 
1837
      slotp->used = 0;
 
1838
      return -1;
 
1839
    }
 
1840
  if (portno < 0 || portno >= slotp->osc.ctx->reader_count)
 
1841
    {
 
1842
      log_error ("no card reader available\n");
 
1843
      sc_release_context (slotp->osc.ctx);
 
1844
      slotp->used = 0;
 
1845
      return -1;
 
1846
    }
 
1847
 
 
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 ();
 
1852
 
 
1853
  if (sc_detect_card_presence (slotp->osc.ctx->reader[portno], 0) != 1)
 
1854
    {
 
1855
      log_error ("no card present\n");
 
1856
      sc_release_context (slotp->osc.ctx);
 
1857
      slotp->used = 0;
 
1858
      return -1;
 
1859
    }
 
1860
  
 
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");
 
1864
  if (err)
 
1865
    {
 
1866
      log_error ("failed to select the iso7816 driver: %s\n",
 
1867
                 sc_strerror (err));
 
1868
      sc_release_context (slotp->osc.ctx);
 
1869
      slotp->used = 0;
 
1870
      return -1;
 
1871
    }
 
1872
 
 
1873
  /* Now connect the card and hope that OpenSC won't try to be too
 
1874
     smart. */
 
1875
  err = sc_connect_card (slotp->osc.ctx->reader[portno], 0,
 
1876
                         &slotp->osc.scard);
 
1877
  if (err)
 
1878
    {
 
1879
      log_error ("failed to connect card in reader %d: %s\n",
 
1880
                 portno, sc_strerror (err));
 
1881
      sc_release_context (slotp->osc.ctx);
 
1882
      slotp->used = 0;
 
1883
      return -1;
 
1884
    }
 
1885
  if (opt.verbose)
 
1886
    log_info ("connected to card in opensc reader %d using driver `%s'\n",
 
1887
              portno, slotp->osc.scard->driver->name);
 
1888
 
 
1889
  err = sc_lock (slotp->osc.scard);
 
1890
  if (err)
 
1891
    {
 
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);
 
1896
      slotp->used = 0;
 
1897
      return -1;
 
1898
    }
 
1899
 
 
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);
 
1904
 
 
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;
 
1910
 
 
1911
  dump_reader_status (slot); 
 
1912
  return slot;
 
1913
}
 
1914
 
 
1915
#endif /* HAVE_OPENSC */
 
1916
 
 
1917
 
 
1918
 
 
1919
#ifdef USE_G10CODE_RAPDU
 
1920
/* 
 
1921
     The Remote APDU Interface.
 
1922
 
 
1923
     This uses the Remote APDU protocol to contact a reader.
 
1924
 
 
1925
     The port number is actually an index into the list of ports as
 
1926
     returned via the protocol.
 
1927
 */
 
1928
 
 
1929
 
 
1930
static int
 
1931
rapdu_status_to_sw (int status)
 
1932
{
 
1933
  int rc;
 
1934
 
 
1935
  switch (status)
 
1936
    {
 
1937
    case RAPDU_STATUS_SUCCESS:  rc = 0; break;
 
1938
 
 
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;
 
1944
 
 
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;
 
1951
 
 
1952
    default: rc = SW_HOST_GENERAL_ERROR; break;
 
1953
    }
 
1954
 
 
1955
  return rc;
 
1956
}
 
1957
 
 
1958
 
 
1959
 
 
1960
static int
 
1961
close_rapdu_reader (int slot)
 
1962
{
 
1963
  rapdu_release (reader_table[slot].rapdu.handle);
 
1964
  reader_table[slot].used = 0;
 
1965
  return 0;
 
1966
}
 
1967
 
 
1968
 
 
1969
static int
 
1970
reset_rapdu_reader (int slot)
 
1971
{
 
1972
  int err;
 
1973
  reader_table_t slotp;
 
1974
  rapdu_msg_t msg = NULL;
 
1975
 
 
1976
  slotp = reader_table + slot;
 
1977
 
 
1978
  err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
 
1979
  if (err)
 
1980
    {
 
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);
 
1985
    }
 
1986
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
1987
  if (err)
 
1988
    {
 
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);
 
1993
    }
 
1994
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
1995
    {
 
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);
 
2000
      return sw;
 
2001
    }
 
2002
  if (msg->datalen >= DIM (slotp->atr))
 
2003
    {
 
2004
      log_error ("ATR returned by the RAPDU layer is too large\n");
 
2005
      rapdu_msg_release (msg);
 
2006
      return SW_HOST_INV_VALUE; 
 
2007
    }
 
2008
  slotp->atrlen = msg->datalen;
 
2009
  memcpy (slotp->atr, msg->data, msg->datalen);
 
2010
 
 
2011
  rapdu_msg_release (msg);
 
2012
  return 0;
 
2013
}
 
2014
 
 
2015
 
 
2016
static int
 
2017
my_rapdu_get_status (int slot, unsigned int *status)
 
2018
{
 
2019
  int err;
 
2020
  reader_table_t slotp;
 
2021
  rapdu_msg_t msg = NULL;
 
2022
  int oldslot;
 
2023
 
 
2024
  slotp = reader_table + slot;
 
2025
 
 
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);
 
2029
  if (err)
 
2030
    {
 
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);
 
2034
    }
 
2035
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2036
  if (err)
 
2037
    {
 
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);
 
2042
    }
 
2043
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2044
    {
 
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);
 
2049
      return sw;
 
2050
    }
 
2051
  *status = msg->data[0];
 
2052
 
 
2053
  rapdu_msg_release (msg);
 
2054
  return 0;
 
2055
}
 
2056
 
 
2057
 
 
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. */
 
2061
static int
 
2062
my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
2063
                    unsigned char *buffer, size_t *buflen)
 
2064
{
 
2065
  int err;
 
2066
  reader_table_t slotp;
 
2067
  rapdu_msg_t msg = NULL;
 
2068
  size_t maxlen = *buflen;
 
2069
 
 
2070
  slotp = reader_table + slot;
 
2071
 
 
2072
  *buflen = 0;
 
2073
  if (DBG_CARD_IO)
 
2074
    log_printhex ("  APDU_data:", apdu, apdulen);
 
2075
 
 
2076
  if (apdulen < 4)
 
2077
    {
 
2078
      log_error ("rapdu_send_apdu: APDU is too short\n");
 
2079
      return SW_HOST_INV_VALUE;
 
2080
    }
 
2081
 
 
2082
  err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
 
2083
  if (err)
 
2084
    {
 
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);
 
2089
    }
 
2090
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2091
  if (err)
 
2092
    {
 
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);
 
2097
    }
 
2098
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2099
    {
 
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);
 
2104
      return sw;
 
2105
    }
 
2106
  
 
2107
  if (msg->datalen > maxlen)
 
2108
    {
 
2109
      log_error ("rapdu response apdu too large\n");
 
2110
      rapdu_msg_release (msg);
 
2111
      return SW_HOST_INV_VALUE; 
 
2112
    }
 
2113
 
 
2114
  *buflen = msg->datalen;
 
2115
  memcpy (buffer, msg->data, msg->datalen);
 
2116
 
 
2117
  rapdu_msg_release (msg);
 
2118
  return 0;
 
2119
}
 
2120
 
 
2121
static int
 
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)
 
2132
{
 
2133
  int err;
 
2134
  int slot;
 
2135
  reader_table_t slotp;
 
2136
  rapdu_msg_t msg = NULL;
 
2137
 
 
2138
  slot = new_reader_slot ();
 
2139
  if (slot == -1)
 
2140
    return -1;
 
2141
  slotp = reader_table + slot;
 
2142
 
 
2143
  slotp->rapdu.handle = rapdu_new ();
 
2144
  if (!slotp->rapdu.handle)
 
2145
    {
 
2146
      slotp->used = 0;
 
2147
      return -1;
 
2148
    }
 
2149
 
 
2150
 
 
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);
 
2156
 
 
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);
 
2162
  if (err)
 
2163
    {
 
2164
      log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
 
2165
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2166
      goto failure;
 
2167
    }
 
2168
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2169
  if (err)
 
2170
    {
 
2171
      log_info ("receiving rapdu message failed: %s\n",
 
2172
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2173
      goto failure;
 
2174
    }
 
2175
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2176
    {
 
2177
      log_info ("rapdu command GET ATR failed: %s\n",
 
2178
                 rapdu_strerror (msg->cmd));
 
2179
      goto failure;
 
2180
    }
 
2181
  if (msg->datalen >= DIM (slotp->atr))
 
2182
    {
 
2183
      log_error ("ATR returned by the RAPDU layer is too large\n");
 
2184
      goto failure;
 
2185
    }
 
2186
  slotp->atrlen = msg->datalen;
 
2187
  memcpy (slotp->atr, msg->data, msg->datalen);
 
2188
 
 
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;
 
2194
 
 
2195
  dump_reader_status (slot); 
 
2196
  rapdu_msg_release (msg);
 
2197
  return slot;
 
2198
 
 
2199
 failure:      
 
2200
  rapdu_msg_release (msg);
 
2201
  rapdu_release (slotp->rapdu.handle);
 
2202
  slotp->used = 0;
 
2203
  return -1;
 
2204
}
 
2205
 
 
2206
#endif /*USE_G10CODE_RAPDU*/
 
2207
 
 
2208
 
 
2209
 
 
2210
/* 
 
2211
       Driver Access
 
2212
 */
 
2213
 
 
2214
 
 
2215
static int
 
2216
lock_slot (int slot)
 
2217
{
 
2218
#ifdef USE_GNU_PTH
 
2219
  if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
 
2220
    {
 
2221
      log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
 
2222
      return SW_HOST_LOCKING_FAILED;
 
2223
    }
 
2224
#endif /*USE_GNU_PTH*/
 
2225
  return 0;
 
2226
}
 
2227
 
 
2228
static int
 
2229
trylock_slot (int slot)
 
2230
{
 
2231
#ifdef USE_GNU_PTH
 
2232
  if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
 
2233
    {
 
2234
      if (errno == EBUSY)
 
2235
        return SW_HOST_BUSY;
 
2236
      log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
 
2237
      return SW_HOST_LOCKING_FAILED;
 
2238
    }
 
2239
#endif /*USE_GNU_PTH*/
 
2240
  return 0;
 
2241
}
 
2242
 
 
2243
static void
 
2244
unlock_slot (int slot)
 
2245
{
 
2246
#ifdef USE_GNU_PTH
 
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*/
 
2250
}
 
2251
 
 
2252
 
 
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. */
 
2257
int
 
2258
apdu_open_reader (const char *portstr)
 
2259
{
 
2260
  static int pcsc_api_loaded, ct_api_loaded;
 
2261
 
 
2262
#ifdef HAVE_LIBUSB
 
2263
  if (!opt.disable_ccid)
 
2264
    {
 
2265
      int slot, i;
 
2266
      const char *s;
 
2267
 
 
2268
      slot = open_ccid_reader (portstr);
 
2269
      if (slot != -1)
 
2270
        return slot; /* got one */
 
2271
 
 
2272
      /* If a CCID reader specification has been given, the user does
 
2273
         not want a fallback to other drivers. */
 
2274
      if (portstr)
 
2275
        for (s=portstr, i=0; *s; s++)
 
2276
          if (*s == ':' && (++i == 3))
 
2277
            return -1;
 
2278
    }
 
2279
 
 
2280
#endif /* HAVE_LIBUSB */
 
2281
 
 
2282
#ifdef HAVE_OPENSC
 
2283
  if (!opt.disable_opensc)
 
2284
    {
 
2285
      int port = portstr? atoi (portstr) : 0;
 
2286
 
 
2287
      return open_osc_reader (port);
 
2288
    }
 
2289
#endif /* HAVE_OPENSC */  
 
2290
 
 
2291
 
 
2292
  if (opt.ctapi_driver && *opt.ctapi_driver)
 
2293
    {
 
2294
      int port = portstr? atoi (portstr) : 32768;
 
2295
 
 
2296
      if (!ct_api_loaded)
 
2297
        {
 
2298
          void *handle;
 
2299
          
 
2300
          handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
 
2301
          if (!handle)
 
2302
            {
 
2303
              log_error ("apdu_open_reader: failed to open driver: %s\n",
 
2304
                         dlerror ());
 
2305
              return -1;
 
2306
            }
 
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)
 
2311
            {
 
2312
              log_error ("apdu_open_reader: invalid CT-API driver\n");
 
2313
              dlclose (handle);
 
2314
              return -1;
 
2315
            }
 
2316
          ct_api_loaded = 1;
 
2317
        }
 
2318
      return open_ct_reader (port);
 
2319
    }
 
2320
 
 
2321
  
 
2322
  /* No ctAPI configured, so lets try the PC/SC API */
 
2323
  if (!pcsc_api_loaded)
 
2324
    {
 
2325
#ifndef NEED_PCSC_WRAPPER
 
2326
      void *handle;
 
2327
 
 
2328
      handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
 
2329
      if (!handle)
 
2330
        {
 
2331
          log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
 
2332
                     opt.pcsc_driver, dlerror ());
 
2333
          return -1;
 
2334
        }
 
2335
 
 
2336
      pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
 
2337
      pcsc_release_context   = dlsym (handle, "SCardReleaseContext");
 
2338
      pcsc_list_readers      = dlsym (handle, "SCardListReaders");
 
2339
#ifdef _WIN32
 
2340
      if (!pcsc_list_readers)
 
2341
        pcsc_list_readers    = dlsym (handle, "SCardListReadersA");
 
2342
#endif
 
2343
      pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
 
2344
#ifdef _WIN32
 
2345
      if (!pcsc_get_status_change)
 
2346
        pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
 
2347
#endif
 
2348
      pcsc_connect           = dlsym (handle, "SCardConnect");
 
2349
#ifdef _WIN32
 
2350
      if (!pcsc_connect)
 
2351
        pcsc_connect         = dlsym (handle, "SCardConnectA");
 
2352
#endif
 
2353
      pcsc_reconnect         = dlsym (handle, "SCardReconnect");
 
2354
#ifdef _WIN32
 
2355
      if (!pcsc_reconnect)
 
2356
        pcsc_reconnect       = dlsym (handle, "SCardReconnectA");
 
2357
#endif
 
2358
      pcsc_disconnect        = dlsym (handle, "SCardDisconnect");
 
2359
      pcsc_status            = dlsym (handle, "SCardStatus");
 
2360
#ifdef _WIN32
 
2361
      if (!pcsc_status)
 
2362
        pcsc_status          = dlsym (handle, "SCardStatusA");
 
2363
#endif
 
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");
 
2368
 
 
2369
      if (!pcsc_establish_context
 
2370
          || !pcsc_release_context  
 
2371
          || !pcsc_list_readers     
 
2372
          || !pcsc_get_status_change
 
2373
          || !pcsc_connect          
 
2374
          || !pcsc_reconnect
 
2375
          || !pcsc_disconnect
 
2376
          || !pcsc_status
 
2377
          || !pcsc_begin_transaction
 
2378
          || !pcsc_end_transaction
 
2379
          || !pcsc_transmit         
 
2380
          /* || !pcsc_set_timeout */)
 
2381
        {
 
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,     
 
2390
                     !!pcsc_connect,          
 
2391
                     !!pcsc_reconnect,          
 
2392
                     !!pcsc_disconnect,
 
2393
                     !!pcsc_status,
 
2394
                     !!pcsc_begin_transaction,
 
2395
                     !!pcsc_end_transaction,
 
2396
                     !!pcsc_transmit,         
 
2397
                     !!pcsc_set_timeout );
 
2398
          dlclose (handle);
 
2399
          return -1;
 
2400
        }
 
2401
#endif /*!NEED_PCSC_WRAPPER*/  
 
2402
      pcsc_api_loaded = 1;
 
2403
    }
 
2404
 
 
2405
  return open_pcsc_reader (portstr);
 
2406
}
 
2407
 
 
2408
 
 
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.
 
2413
 
 
2414
   If PORTSTR is NULL we default to the first availabe port.
 
2415
*/  
 
2416
int
 
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)
 
2427
{
 
2428
#ifdef USE_G10CODE_RAPDU
 
2429
  return open_rapdu_reader (portstr? atoi (portstr) : 0,
 
2430
                            cookie, length,
 
2431
                            readfnc, readfnc_value,
 
2432
                            writefnc, writefnc_value,
 
2433
                            closefnc, closefnc_value);
 
2434
#else
 
2435
#ifdef _WIN32 
 
2436
  errno = ENOENT;
 
2437
#else
 
2438
  errno = ENOSYS;
 
2439
#endif
 
2440
  return -1;
 
2441
#endif
 
2442
}
 
2443
 
 
2444
 
 
2445
int
 
2446
apdu_close_reader (int slot)
 
2447
{
 
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;
 
2453
}
 
2454
 
 
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. */
 
2458
int
 
2459
apdu_shutdown_reader (int slot)
 
2460
{
 
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;
 
2466
}
 
2467
 
 
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. */
 
2471
int
 
2472
apdu_enum_reader (int slot, int *used)
 
2473
{
 
2474
  if (slot < 0 || slot >= MAX_READER)
 
2475
    return SW_HOST_NO_DRIVER;
 
2476
  *used = reader_table[slot].used;
 
2477
  return 0;
 
2478
}
 
2479
 
 
2480
/* Do a reset for the card in reader at SLOT. */
 
2481
int
 
2482
apdu_reset (int slot)
 
2483
{
 
2484
  int sw;
 
2485
 
 
2486
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2487
    return SW_HOST_NO_DRIVER;
 
2488
  
 
2489
  if ((sw = lock_slot (slot)))
 
2490
    return sw;
 
2491
 
 
2492
  reader_table[slot].last_status = 0;
 
2493
  if (reader_table[slot].reset_reader)
 
2494
    sw = reader_table[slot].reset_reader (slot);
 
2495
 
 
2496
  if (!sw)
 
2497
    {
 
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);
 
2501
    }
 
2502
 
 
2503
  unlock_slot (slot);
 
2504
  return sw;
 
2505
}
 
2506
 
 
2507
 
 
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
 
2511
   locked card. */
 
2512
int
 
2513
apdu_activate (int slot)
 
2514
{
 
2515
  int sw;
 
2516
  unsigned int s;
 
2517
 
 
2518
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2519
    return SW_HOST_NO_DRIVER;
 
2520
  
 
2521
  if ((sw = trylock_slot (slot)))
 
2522
    return sw;
 
2523
 
 
2524
  if (reader_table[slot].get_status_reader)
 
2525
    sw = reader_table[slot].get_status_reader (slot, &s);
 
2526
 
 
2527
  if (!sw)
 
2528
    {
 
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 )
 
2533
        {
 
2534
          /* We don't have an ATR or a card is present though inactive:
 
2535
             do a reset now. */
 
2536
          if (reader_table[slot].reset_reader)
 
2537
            {
 
2538
              reader_table[slot].last_status = 0;
 
2539
              sw = reader_table[slot].reset_reader (slot);
 
2540
              if (!sw)
 
2541
                {
 
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);
 
2545
                }
 
2546
            }
 
2547
        }
 
2548
    }
 
2549
  
 
2550
  unlock_slot (slot);
 
2551
  return sw;
 
2552
}
 
2553
 
 
2554
  
 
2555
 
 
2556
unsigned char *
 
2557
apdu_get_atr (int slot, size_t *atrlen)
 
2558
{
 
2559
  char *buf;
 
2560
 
 
2561
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2562
    return NULL;
 
2563
  
 
2564
  buf = xtrymalloc (reader_table[slot].atrlen);
 
2565
  if (!buf)
 
2566
    return NULL;
 
2567
  memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
 
2568
  *atrlen = reader_table[slot].atrlen;
 
2569
  return buf;
 
2570
}
 
2571
 
 
2572
 
 
2573
    
 
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
 
2577
 
 
2578
     bit 0 = card present and usable
 
2579
     bit 1 = card present
 
2580
     bit 2 = card active
 
2581
     bit 3 = card access locked [not yet implemented]
 
2582
 
 
2583
   For must application, testing bit 0 is sufficient.
 
2584
 
 
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
 
2587
   change.
 
2588
*/
 
2589
int
 
2590
apdu_get_status (int slot, int hang,
 
2591
                 unsigned int *status, unsigned int *changed)
 
2592
{
 
2593
  int sw;
 
2594
  unsigned int s;
 
2595
 
 
2596
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2597
    return SW_HOST_NO_DRIVER;
 
2598
 
 
2599
  if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
 
2600
    return sw;
 
2601
 
 
2602
  if (reader_table[slot].get_status_reader)
 
2603
    sw = reader_table[slot].get_status_reader (slot, &s);
 
2604
 
 
2605
  unlock_slot (slot);
 
2606
 
 
2607
  if (sw)
 
2608
    {
 
2609
      reader_table[slot].last_status = 0;
 
2610
      return sw;
 
2611
    }
 
2612
 
 
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 )
 
2617
    {
 
2618
      reader_table[slot].change_counter++;
 
2619
      /* Make sure that the ATR is invalid so that a reset will be by
 
2620
         activate.  */
 
2621
      reader_table[slot].atrlen = 0;
 
2622
    }
 
2623
  reader_table[slot].last_status = (s | 0x8000);
 
2624
 
 
2625
  if (status)
 
2626
    *status = s;
 
2627
  if (changed)
 
2628
    *changed = reader_table[slot].change_counter;
 
2629
  return 0;
 
2630
}
 
2631
 
 
2632
 
 
2633
/* Dispatcher for the actual send_apdu function. Note, that this
 
2634
   function should be called in locked state. */
 
2635
static int
 
2636
send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
2637
           unsigned char *buffer, size_t *buflen)
 
2638
{
 
2639
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2640
    return SW_HOST_NO_DRIVER;
 
2641
 
 
2642
  if (reader_table[slot].send_apdu_reader)
 
2643
    return reader_table[slot].send_apdu_reader (slot,
 
2644
                                                apdu, apdulen,
 
2645
                                                buffer, buflen);
 
2646
  else
 
2647
    return SW_HOST_NOT_SUPPORTED;
 
2648
}
 
2649
 
 
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.  */
 
2659
int 
 
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)
 
2663
{
 
2664
#define RESULTLEN 256
 
2665
  unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
 
2666
                                         the driver. */
 
2667
  size_t resultlen;
 
2668
  unsigned char apdu[5+256+1];
 
2669
  size_t apdulen;
 
2670
  int sw;
 
2671
  long rc; /* we need a long here due to PC/SC. */
 
2672
 
 
2673
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2674
    return SW_HOST_NO_DRIVER;
 
2675
 
 
2676
  if (DBG_CARD_IO)
 
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);
 
2679
 
 
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;
 
2686
 
 
2687
  if ((sw = lock_slot (slot)))
 
2688
    return sw;
 
2689
 
 
2690
  apdulen = 0;
 
2691
  apdu[apdulen++] = class;
 
2692
  apdu[apdulen++] = ins;
 
2693
  apdu[apdulen++] = p0;
 
2694
  apdu[apdulen++] = p1;
 
2695
  if (lc != -1)
 
2696
    {
 
2697
      apdu[apdulen++] = lc;
 
2698
      memcpy (apdu+apdulen, data, lc);
 
2699
      apdulen += lc;
 
2700
    }
 
2701
  if (le != -1)
 
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)
 
2709
    {
 
2710
      log_error ("apdu_send_simple(%d) failed: %s\n",
 
2711
                 slot, apdu_strerror (rc));
 
2712
      unlock_slot (slot);
 
2713
      return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2714
    }
 
2715
  sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2716
  /* store away the returned data but strip the statusword. */
 
2717
  resultlen -= 2;
 
2718
  if (DBG_CARD_IO)
 
2719
    {
 
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);
 
2724
    }
 
2725
 
 
2726
  if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
 
2727
    {
 
2728
      if (retbuf)
 
2729
        {
 
2730
          *retbuf = xtrymalloc (resultlen? resultlen : 1);
 
2731
          if (!*retbuf)
 
2732
            {
 
2733
              unlock_slot (slot);
 
2734
              return SW_HOST_OUT_OF_CORE;
 
2735
            }
 
2736
          *retbuflen = resultlen;
 
2737
          memcpy (*retbuf, result, resultlen);
 
2738
        }
 
2739
    }
 
2740
  else if ((sw & 0xff00) == SW_MORE_DATA)
 
2741
    {
 
2742
      unsigned char *p = NULL, *tmp;
 
2743
      size_t bufsize = 4096;
 
2744
 
 
2745
      /* It is likely that we need to return much more data, so we
 
2746
         start off with a large buffer. */
 
2747
      if (retbuf)
 
2748
        {
 
2749
          *retbuf = p = xtrymalloc (bufsize);
 
2750
          if (!*retbuf)
 
2751
            {
 
2752
              unlock_slot (slot);
 
2753
              return SW_HOST_OUT_OF_CORE;
 
2754
            }
 
2755
          assert (resultlen < bufsize);
 
2756
          memcpy (p, result, resultlen);
 
2757
          p += resultlen;
 
2758
        }
 
2759
 
 
2760
      do
 
2761
        {
 
2762
          int len = (sw & 0x00ff);
 
2763
          
 
2764
          if (DBG_CARD_IO)
 
2765
            log_debug ("apdu_send_simple(%d): %d more bytes available\n",
 
2766
                       slot, len);
 
2767
          apdulen = 0;
 
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)
 
2777
            {
 
2778
              log_error ("apdu_send_simple(%d) for get response failed: %s\n",
 
2779
                         slot, apdu_strerror (rc));
 
2780
              unlock_slot (slot);
 
2781
              return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2782
            }
 
2783
          sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2784
          resultlen -= 2;
 
2785
          if (DBG_CARD_IO)
 
2786
            {
 
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);
 
2791
            }
 
2792
 
 
2793
          if ((sw & 0xff00) == SW_MORE_DATA
 
2794
              || sw == SW_SUCCESS
 
2795
              || sw == SW_EOF_REACHED )
 
2796
            {
 
2797
              if (retbuf && resultlen)
 
2798
                {
 
2799
                  if (p - *retbuf + resultlen > bufsize)
 
2800
                    {
 
2801
                      bufsize += resultlen > 4096? resultlen: 4096;
 
2802
                      tmp = xtryrealloc (*retbuf, bufsize);
 
2803
                      if (!tmp)
 
2804
                        {
 
2805
                          unlock_slot (slot);
 
2806
                          return SW_HOST_OUT_OF_CORE;
 
2807
                        }
 
2808
                      p = tmp + (p - *retbuf);
 
2809
                      *retbuf = tmp;
 
2810
                    }
 
2811
                  memcpy (p, result, resultlen);
 
2812
                  p += resultlen;
 
2813
                }
 
2814
            }
 
2815
          else
 
2816
            log_info ("apdu_send_simple(%d) "
 
2817
                      "got unexpected status %04X from get response\n",
 
2818
                      slot, sw);
 
2819
        }
 
2820
      while ((sw & 0xff00) == SW_MORE_DATA);
 
2821
      
 
2822
      if (retbuf)
 
2823
        {
 
2824
          *retbuflen = p - *retbuf;
 
2825
          tmp = xtryrealloc (*retbuf, *retbuflen);
 
2826
          if (tmp)
 
2827
            *retbuf = tmp;
 
2828
        }
 
2829
    }
 
2830
 
 
2831
  unlock_slot (slot);
 
2832
 
 
2833
  if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
 
2834
    log_printhex ("      dump: ", *retbuf, *retbuflen);
 
2835
 
 
2836
  return sw;
 
2837
#undef RESULTLEN
 
2838
}
 
2839
 
 
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
 
2848
   errors.  */
 
2849
int 
 
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)
 
2852
{
 
2853
  return apdu_send_le (slot, class, ins, p0, p1, lc, data, 256, 
 
2854
                       retbuf, retbuflen);
 
2855
}
 
2856
 
 
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
 
2862
   returned. */
 
2863
int 
 
2864
apdu_send_simple (int slot, int class, int ins, int p0, int p1,
 
2865
                  int lc, const char *data)
 
2866
{
 
2867
  return apdu_send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL);
 
2868
}
 
2869
 
 
2870
 
 
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
 
2878
   immediately.*/
 
2879
int 
 
2880
apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
 
2881
                  int handle_more,
 
2882
                  unsigned char **retbuf, size_t *retbuflen)
 
2883
{
 
2884
#define RESULTLEN 256
 
2885
  unsigned char apdu[5+256+1];
 
2886
  size_t apdulen;
 
2887
  unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
 
2888
                                         the driver. */
 
2889
  size_t resultlen;
 
2890
  int sw;
 
2891
  long rc; /* we need a long here due to PC/SC. */
 
2892
  int class;
 
2893
 
 
2894
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2895
    return SW_HOST_NO_DRIVER;
 
2896
 
 
2897
  if ((sw = trylock_slot (slot)))
 
2898
    return sw;
 
2899
 
 
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;
 
2906
 
 
2907
 
 
2908
  rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
 
2909
  if (rc || resultlen < 2)
 
2910
    {
 
2911
      log_error ("apdu_send_direct(%d) failed: %s\n",
 
2912
                 slot, apdu_strerror (rc));
 
2913
      unlock_slot (slot);
 
2914
      return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2915
    }
 
2916
  sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2917
  /* Store away the returned data but strip the statusword. */
 
2918
  resultlen -= 2;
 
2919
  if (DBG_CARD_IO)
 
2920
    {
 
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);
 
2925
    }
 
2926
 
 
2927
  if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
 
2928
    {
 
2929
      unsigned char *p = NULL, *tmp;
 
2930
      size_t bufsize = 4096;
 
2931
 
 
2932
      /* It is likely that we need to return much more data, so we
 
2933
         start off with a large buffer. */
 
2934
      if (retbuf)
 
2935
        {
 
2936
          *retbuf = p = xtrymalloc (bufsize + 2);
 
2937
          if (!*retbuf)
 
2938
            {
 
2939
              unlock_slot (slot);
 
2940
              return SW_HOST_OUT_OF_CORE;
 
2941
            }
 
2942
          assert (resultlen < bufsize);
 
2943
          memcpy (p, result, resultlen);
 
2944
          p += resultlen;
 
2945
        }
 
2946
 
 
2947
      do
 
2948
        {
 
2949
          int len = (sw & 0x00ff);
 
2950
          
 
2951
          if (DBG_CARD_IO)
 
2952
            log_debug ("apdu_send_direct(%d): %d more bytes available\n",
 
2953
                       slot, len);
 
2954
          apdulen = 0;
 
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)
 
2964
            {
 
2965
              log_error ("apdu_send_direct(%d) for get response failed: %s\n",
 
2966
                         slot, apdu_strerror (rc));
 
2967
              unlock_slot (slot);
 
2968
              return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2969
            }
 
2970
          sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2971
          resultlen -= 2;
 
2972
          if (DBG_CARD_IO)
 
2973
            {
 
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);
 
2978
            }
 
2979
 
 
2980
          if ((sw & 0xff00) == SW_MORE_DATA
 
2981
              || sw == SW_SUCCESS
 
2982
              || sw == SW_EOF_REACHED )
 
2983
            {
 
2984
              if (retbuf && resultlen)
 
2985
                {
 
2986
                  if (p - *retbuf + resultlen > bufsize)
 
2987
                    {
 
2988
                      bufsize += resultlen > 4096? resultlen: 4096;
 
2989
                      tmp = xtryrealloc (*retbuf, bufsize + 2);
 
2990
                      if (!tmp)
 
2991
                        {
 
2992
                          unlock_slot (slot);
 
2993
                          return SW_HOST_OUT_OF_CORE;
 
2994
                        }
 
2995
                      p = tmp + (p - *retbuf);
 
2996
                      *retbuf = tmp;
 
2997
                    }
 
2998
                  memcpy (p, result, resultlen);
 
2999
                  p += resultlen;
 
3000
                }
 
3001
            }
 
3002
          else
 
3003
            log_info ("apdu_send_sdirect(%d) "
 
3004
                      "got unexpected status %04X from get response\n",
 
3005
                      slot, sw);
 
3006
        }
 
3007
      while ((sw & 0xff00) == SW_MORE_DATA);
 
3008
      
 
3009
      if (retbuf)
 
3010
        {
 
3011
          *retbuflen = p - *retbuf;
 
3012
          tmp = xtryrealloc (*retbuf, *retbuflen + 2);
 
3013
          if (tmp)
 
3014
            *retbuf = tmp;
 
3015
        }
 
3016
    }
 
3017
  else
 
3018
    {
 
3019
      if (retbuf)
 
3020
        {
 
3021
          *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
 
3022
          if (!*retbuf)
 
3023
            {
 
3024
              unlock_slot (slot);
 
3025
              return SW_HOST_OUT_OF_CORE;
 
3026
            }
 
3027
          *retbuflen = resultlen;
 
3028
          memcpy (*retbuf, result, resultlen);
 
3029
        }
 
3030
    }
 
3031
 
 
3032
  unlock_slot (slot);
 
3033
 
 
3034
  /* Append the status word - we reseved the two extra bytes while
 
3035
     allocating the buffer. */
 
3036
  if (retbuf)
 
3037
    {
 
3038
      (*retbuf)[(*retbuflen)++] = (sw >> 8);
 
3039
      (*retbuf)[(*retbuflen)++] = sw;
 
3040
    }
 
3041
 
 
3042
  if (DBG_CARD_IO && retbuf)
 
3043
    log_printhex ("      dump: ", *retbuf, *retbuflen);
 
3044
 
 
3045
  return 0;
 
3046
#undef RESULTLEN
 
3047
}
 
3048
 
 
3049