~ubuntu-branches/ubuntu/precise/gnupg2/precise-proposed

« back to all changes in this revision

Viewing changes to scd/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.4.2.24 2004/10/20 08:54:45 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
 
 
69
/* To to conflicting use of threading libraries we usually can't link
 
70
   against libpcsclite.   Instead we use a wrapper program.  */
 
71
#ifdef USE_GNU_PTH
 
72
#ifndef HAVE_W32_SYSTEM
 
73
#define NEED_PCSC_WRAPPER 1
 
74
#endif
 
75
#endif
 
76
 
 
77
 
 
78
#define MAX_READER 4 /* Number of readers we support concurrently. */
 
79
 
 
80
 
 
81
#ifdef _WIN32
 
82
#define DLSTDCALL __stdcall
 
83
#else
 
84
#define DLSTDCALL
 
85
#endif
 
86
 
 
87
#ifdef _POSIX_OPEN_MAX
 
88
#define MAX_OPEN_FDS _POSIX_OPEN_MAX
 
89
#else
 
90
#define MAX_OPEN_FDS 20
 
91
#endif
 
92
 
 
93
 
 
94
/* A structure to collect information pertaining to one reader
 
95
   slot. */
 
96
struct reader_table_s {
 
97
  int used;            /* True if slot is used. */
 
98
  unsigned short port; /* Port number:  0 = unused, 1 - dev/tty */
 
99
 
 
100
  /* Function pointers intialized to the various backends.  */
 
101
  int (*close_reader)(int);
 
102
  int (*shutdown_reader)(int);
 
103
  int (*reset_reader)(int);
 
104
  int (*get_status_reader)(int, unsigned int *);
 
105
  int (*send_apdu_reader)(int,unsigned char *,size_t,
 
106
                          unsigned char *, size_t *);
 
107
  void (*dump_status_reader)(int);
 
108
 
 
109
  struct {
 
110
    ccid_driver_t handle;
 
111
  } ccid;
 
112
  struct {
 
113
    unsigned long context;
 
114
    unsigned long card;
 
115
    unsigned long protocol;
 
116
#ifdef NEED_PCSC_WRAPPER
 
117
    int req_fd;
 
118
    int rsp_fd;
 
119
    pid_t pid;
 
120
#endif /*NEED_PCSC_WRAPPER*/
 
121
  } pcsc;
 
122
#ifdef HAVE_OPENSC
 
123
  struct {
 
124
    struct sc_context *ctx;
 
125
    struct sc_card *scard;
 
126
  } osc;
 
127
#endif /*HAVE_OPENSC*/
 
128
#ifdef USE_G10CODE_RAPDU
 
129
  struct {
 
130
    rapdu_t handle;
 
131
  } rapdu;
 
132
#endif /*USE_G10CODE_RAPDU*/
 
133
  char *rdrname;     /* Name of the connected reader or NULL if unknown. */
 
134
  int last_status;
 
135
  int status;
 
136
  unsigned char atr[33];
 
137
  size_t atrlen;           /* A zero length indicates that the ATR has
 
138
                              not yet been read; i.e. the card is not
 
139
                              ready for use. */
 
140
  unsigned int change_counter;
 
141
#ifdef USE_GNU_PTH
 
142
  int lock_initialized;
 
143
  pth_mutex_t lock;
 
144
#endif
 
145
};
 
146
typedef struct reader_table_s *reader_table_t;
 
147
 
 
148
/* A global table to keep track of active readers. */
 
149
static struct reader_table_s reader_table[MAX_READER];
 
150
 
 
151
 
 
152
/* ct API function pointer. */
 
153
static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
 
154
static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
 
155
                                   unsigned char *sad, unsigned short lc,
 
156
                                   unsigned char *cmd, unsigned short *lr,
 
157
                                   unsigned char *rsp);
 
158
static char (* DLSTDCALL CT_close) (unsigned short ctn);
 
159
 
 
160
/* PC/SC constants and function pointer. */
 
161
#define PCSC_SCOPE_USER      0 
 
162
#define PCSC_SCOPE_TERMINAL  1 
 
163
#define PCSC_SCOPE_SYSTEM    2 
 
164
#define PCSC_SCOPE_GLOBAL    3 
 
165
 
 
166
#define PCSC_PROTOCOL_T0     1 
 
167
#define PCSC_PROTOCOL_T1     2 
 
168
#define PCSC_PROTOCOL_RAW    4 
 
169
 
 
170
#define PCSC_SHARE_EXCLUSIVE 1
 
171
#define PCSC_SHARE_SHARED    2
 
172
#define PCSC_SHARE_DIRECT    3
 
173
 
 
174
#define PCSC_LEAVE_CARD      0
 
175
#define PCSC_RESET_CARD      1
 
176
#define PCSC_UNPOWER_CARD    2
 
177
#define PCSC_EJECT_CARD      3
 
178
 
 
179
#define PCSC_UNKNOWN    0x0001  
 
180
#define PCSC_ABSENT     0x0002  /* Card is absent.  */
 
181
#define PCSC_PRESENT    0x0004  /* Card is present.  */
 
182
#define PCSC_SWALLOWED  0x0008  /* Card is present and electrical connected. */
 
183
#define PCSC_POWERED    0x0010  /* Card is powered.  */
 
184
#define PCSC_NEGOTIABLE 0x0020  /* Card is awaiting PTS.  */
 
185
#define PCSC_SPECIFIC   0x0040  /* Card is ready for use.  */
 
186
 
 
187
#define PCSC_STATE_UNAWARE     0x0000  /* Want status.  */
 
188
#define PCSC_STATE_IGNORE      0x0001  /* Ignore this reader.  */
 
189
#define PCSC_STATE_CHANGED     0x0002  /* State has changed.  */
 
190
#define PCSC_STATE_UNKNOWN     0x0004  /* Reader unknown.  */
 
191
#define PCSC_STATE_UNAVAILABLE 0x0008  /* Status unavailable.  */
 
192
#define PCSC_STATE_EMPTY       0x0010  /* Card removed.  */
 
193
#define PCSC_STATE_PRESENT     0x0020  /* Card inserted.  */
 
194
#define PCSC_STATE_ATRMATCH    0x0040  /* ATR matches card. */
 
195
#define PCSC_STATE_EXCLUSIVE   0x0080  /* Exclusive Mode.  */
 
196
#define PCSC_STATE_INUSE       0x0100  /* Shared mode.  */
 
197
#define PCSC_STATE_MUTE        0x0200  /* Unresponsive card.  */
 
198
 
 
199
 
 
200
struct pcsc_io_request_s 
 
201
{
 
202
  unsigned long protocol; 
 
203
  unsigned long pci_len;
 
204
};
 
205
 
 
206
typedef struct pcsc_io_request_s *pcsc_io_request_t;
 
207
 
 
208
struct pcsc_readerstate_s
 
209
{
 
210
  const char *reader;
 
211
  void *user_data;
 
212
  unsigned long current_state;
 
213
  unsigned long event_state;
 
214
  unsigned long atrlen;
 
215
  unsigned char atr[33];
 
216
};
 
217
 
 
218
typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
 
219
 
 
220
long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
 
221
                                           const void *reserved1,
 
222
                                           const void *reserved2,
 
223
                                           unsigned long *r_context);
 
224
long (* DLSTDCALL pcsc_release_context) (unsigned long context);
 
225
long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
 
226
                                      const char *groups,
 
227
                                      char *readers, unsigned long*readerslen);
 
228
long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
 
229
                                           unsigned long timeout,
 
230
                                           pcsc_readerstate_t readerstates,
 
231
                                           unsigned long nreaderstates);
 
232
long (* DLSTDCALL pcsc_connect) (unsigned long context,
 
233
                                 const char *reader,
 
234
                                 unsigned long share_mode,
 
235
                                 unsigned long preferred_protocols,
 
236
                                 unsigned long *r_card,
 
237
                                 unsigned long *r_active_protocol);
 
238
long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
 
239
                                   unsigned long share_mode,
 
240
                                   unsigned long preferred_protocols,
 
241
                                   unsigned long initialization,
 
242
                                   unsigned long *r_active_protocol);
 
243
long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
 
244
                                    unsigned long disposition);
 
245
long (* DLSTDCALL pcsc_status) (unsigned long card,
 
246
                                char *reader, unsigned long *readerlen,
 
247
                                unsigned long *r_state,
 
248
                                unsigned long *r_protocol,
 
249
                                unsigned char *atr, unsigned long *atrlen);
 
250
long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
 
251
long (* DLSTDCALL pcsc_end_transaction) (unsigned long card);
 
252
long (* DLSTDCALL pcsc_transmit) (unsigned long card,
 
253
                                  const pcsc_io_request_t send_pci,
 
254
                                  const unsigned char *send_buffer,
 
255
                                  unsigned long send_len,
 
256
                                  pcsc_io_request_t recv_pci,
 
257
                                  unsigned char *recv_buffer,
 
258
                                  unsigned long *recv_len);
 
259
long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
 
260
                                     unsigned long timeout);
 
261
 
 
262
 
 
263
 
 
264
 
 
265
/* 
 
266
      Helper
 
267
 */
 
268
 
 
269
 
 
270
/* Find an unused reader slot for PORTSTR and put it into the reader
 
271
   table.  Return -1 on error or the index into the reader table. */
 
272
static int 
 
273
new_reader_slot (void)    
 
274
{
 
275
  int i, reader = -1;
 
276
 
 
277
  for (i=0; i < MAX_READER; i++)
 
278
    {
 
279
      if (!reader_table[i].used && reader == -1)
 
280
        reader = i;
 
281
    }
 
282
  if (reader == -1)
 
283
    {
 
284
      log_error ("new_reader_slot: out of slots\n");
 
285
      return -1;
 
286
    }
 
287
#ifdef USE_GNU_PTH
 
288
  if (!reader_table[reader].lock_initialized)
 
289
    {
 
290
      if (!pth_mutex_init (&reader_table[reader].lock))
 
291
        {
 
292
          log_error ("error initializing mutex: %s\n", strerror (errno));
 
293
          return -1;
 
294
        }
 
295
      reader_table[reader].lock_initialized = 1;
 
296
    }
 
297
#endif /*USE_GNU_PTH*/
 
298
  reader_table[reader].close_reader = NULL;
 
299
  reader_table[reader].shutdown_reader = NULL;
 
300
  reader_table[reader].reset_reader = NULL;
 
301
  reader_table[reader].get_status_reader = NULL;
 
302
  reader_table[reader].send_apdu_reader = NULL;
 
303
  reader_table[reader].dump_status_reader = NULL;
 
304
 
 
305
  reader_table[reader].used = 1;
 
306
  reader_table[reader].last_status = 0;
 
307
#ifdef NEED_PCSC_WRAPPER
 
308
  reader_table[reader].pcsc.req_fd = -1;
 
309
  reader_table[reader].pcsc.rsp_fd = -1;
 
310
  reader_table[reader].pcsc.pid = (pid_t)(-1);
 
311
#endif
 
312
 
 
313
  return reader;
 
314
}
 
315
 
 
316
 
 
317
static void
 
318
dump_reader_status (int slot)
 
319
{
 
320
  if (!opt.verbose)
 
321
    return;
 
322
 
 
323
  if (reader_table[slot].dump_status_reader)
 
324
    reader_table[slot].dump_status_reader (slot);
 
325
 
 
326
  if (reader_table[slot].status != -1
 
327
      && reader_table[slot].atrlen)
 
328
    {
 
329
      log_info ("slot %d: ATR=", slot);
 
330
      log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
 
331
    }
 
332
}
 
333
 
 
334
 
 
335
 
 
336
static const char *
 
337
host_sw_string (long err)
 
338
{
 
339
  switch (err)
 
340
    {
 
341
    case 0: return "okay";
 
342
    case SW_HOST_OUT_OF_CORE: return "out of core";
 
343
    case SW_HOST_INV_VALUE: return "invalid value";
 
344
    case SW_HOST_NO_DRIVER: return "no driver";
 
345
    case SW_HOST_NOT_SUPPORTED: return "not supported";
 
346
    case SW_HOST_LOCKING_FAILED: return "locking failed";
 
347
    case SW_HOST_BUSY: return "busy";
 
348
    case SW_HOST_NO_CARD: return "no card";
 
349
    case SW_HOST_CARD_INACTIVE: return "card inactive";
 
350
    case SW_HOST_CARD_IO_ERROR: return "card I/O error";
 
351
    case SW_HOST_GENERAL_ERROR: return "general error";
 
352
    case SW_HOST_NO_READER: return "no reader";
 
353
    case SW_HOST_ABORTED: return "aborted";
 
354
    default: return "unknown host status error";
 
355
    }
 
356
}
 
357
 
 
358
 
 
359
const char *
 
360
apdu_strerror (int rc)
 
361
{
 
362
  switch (rc)
 
363
    {
 
364
    case SW_EOF_REACHED    : return "eof reached";
 
365
    case SW_EEPROM_FAILURE : return "eeprom failure";
 
366
    case SW_WRONG_LENGTH   : return "wrong length";
 
367
    case SW_CHV_WRONG      : return "CHV wrong";
 
368
    case SW_CHV_BLOCKED    : return "CHV blocked";
 
369
    case SW_USE_CONDITIONS : return "use conditions not satisfied";
 
370
    case SW_BAD_PARAMETER  : return "bad parameter";
 
371
    case SW_NOT_SUPPORTED  : return "not supported";
 
372
    case SW_FILE_NOT_FOUND : return "file not found";
 
373
    case SW_RECORD_NOT_FOUND:return "record not found";
 
374
    case SW_REF_NOT_FOUND  : return "reference not found";
 
375
    case SW_BAD_P0_P1      : return "bad P0 or P1";
 
376
    case SW_INS_NOT_SUP    : return "instruction not supported";
 
377
    case SW_CLA_NOT_SUP    : return "class not supported";
 
378
    case SW_SUCCESS        : return "success";
 
379
    default:
 
380
      if ((rc & ~0x00ff) == SW_MORE_DATA)
 
381
        return "more data available";
 
382
      if ( (rc & 0x10000) )
 
383
        return host_sw_string (rc);
 
384
      return "unknown status error";
 
385
    }
 
386
}
 
387
 
 
388
 
 
389
 
 
390
/* 
 
391
       ct API Interface 
 
392
 */
 
393
 
 
394
static const char *
 
395
ct_error_string (long err)
 
396
{
 
397
  switch (err)
 
398
    {
 
399
    case 0: return "okay";
 
400
    case -1: return "invalid data";
 
401
    case -8: return "ct error";
 
402
    case -10: return "transmission error";
 
403
    case -11: return "memory allocation error";
 
404
    case -128: return "HTSI error";
 
405
    default: return "unknown CT-API error";
 
406
    }
 
407
}
 
408
 
 
409
 
 
410
static void
 
411
ct_dump_reader_status (int slot)
 
412
{
 
413
  log_info ("reader slot %d: %s\n", slot,
 
414
            reader_table[slot].status == 1? "Processor ICC present" :
 
415
            reader_table[slot].status == 0? "Memory ICC present" :
 
416
            "ICC not present" );
 
417
}
 
418
 
 
419
 
 
420
/* Wait for the card in SLOT and activate it.  Return a status word
 
421
   error or 0 on success. */
 
422
static int
 
423
ct_activate_card (int slot)
 
424
{
 
425
  int rc;
 
426
  unsigned char dad[1], sad[1], cmd[11], buf[256];
 
427
  unsigned short buflen;
 
428
  
 
429
  /* Check whether card has been inserted. */
 
430
  dad[0] = 1;     /* Destination address: CT. */    
 
431
  sad[0] = 2;     /* Source address: Host. */
 
432
 
 
433
  cmd[0] = 0x20;  /* Class byte. */
 
434
  cmd[1] = 0x13;  /* Request status. */
 
435
  cmd[2] = 0x00;  /* From kernel. */
 
436
  cmd[3] = 0x80;  /* Return card's DO. */
 
437
  cmd[4] = 0x00;
 
438
 
 
439
  buflen = DIM(buf);
 
440
 
 
441
  rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
 
442
  if (rc || buflen < 2 || buf[buflen-2] != 0x90)
 
443
    {
 
444
      log_error ("ct_activate_card: can't get status of reader %d: %s\n",
 
445
                 slot, ct_error_string (rc));
 
446
      return SW_HOST_CARD_IO_ERROR;
 
447
    }
 
448
 
 
449
  /* Connected, now activate the card. */           
 
450
  dad[0] = 1;    /* Destination address: CT. */    
 
451
  sad[0] = 2;    /* Source address: Host. */
 
452
 
 
453
  cmd[0] = 0x20;  /* Class byte. */
 
454
  cmd[1] = 0x12;  /* Request ICC. */
 
455
  cmd[2] = 0x01;  /* From first interface. */
 
456
  cmd[3] = 0x01;  /* Return card's ATR. */
 
457
  cmd[4] = 0x00;
 
458
 
 
459
  buflen = DIM(buf);
 
460
 
 
461
  rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
 
462
  if (rc || buflen < 2 || buf[buflen-2] != 0x90)
 
463
    {
 
464
      log_error ("ct_activate_card(%d): activation failed: %s\n",
 
465
                 slot, ct_error_string (rc));
 
466
      if (!rc)
 
467
        log_printhex ("  received data:", buf, buflen);
 
468
      return SW_HOST_CARD_IO_ERROR;
 
469
    }
 
470
 
 
471
  /* Store the type and the ATR. */
 
472
  if (buflen - 2 > DIM (reader_table[0].atr))
 
473
    {
 
474
      log_error ("ct_activate_card(%d): ATR too long\n", slot);
 
475
      return SW_HOST_CARD_IO_ERROR;
 
476
    }
 
477
 
 
478
  reader_table[slot].status = buf[buflen - 1];
 
479
  memcpy (reader_table[slot].atr, buf, buflen - 2);
 
480
  reader_table[slot].atrlen = buflen - 2;
 
481
  return 0;
 
482
}
 
483
 
 
484
 
 
485
static int
 
486
close_ct_reader (int slot)
 
487
{
 
488
  CT_close (slot);
 
489
  reader_table[slot].used = 0;
 
490
  return 0;
 
491
}
 
492
 
 
493
static int
 
494
reset_ct_reader (int slot)
 
495
{
 
496
  /* FIXME: Check is this is sufficient do do a reset. */
 
497
  return ct_activate_card (slot);
 
498
}
 
499
 
 
500
 
 
501
static int
 
502
ct_get_status (int slot, unsigned int *status)
 
503
{
 
504
  *status = 1|2|4;  /* FIXME */
 
505
  return 0;
 
506
 
 
507
  return SW_HOST_NOT_SUPPORTED;
 
508
}
 
509
 
 
510
/* Actually send the APDU of length APDULEN to SLOT and return a
 
511
   maximum of *BUFLEN data in BUFFER, the actual retruned size will be
 
512
   set to BUFLEN.  Returns: CT API error code. */
 
513
static int
 
514
ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
515
              unsigned char *buffer, size_t *buflen)
 
516
{
 
517
  int rc;
 
518
  unsigned char dad[1], sad[1];
 
519
  unsigned short ctbuflen;
 
520
  
 
521
  /* If we don't have an ATR, we need to reset the reader first. */
 
522
  if (!reader_table[slot].atrlen
 
523
      && (rc = reset_ct_reader (slot)))
 
524
    return rc;
 
525
 
 
526
  dad[0] = 0;     /* Destination address: Card. */    
 
527
  sad[0] = 2;     /* Source address: Host. */
 
528
  ctbuflen = *buflen;
 
529
  if (DBG_CARD_IO)
 
530
    log_printhex ("  CT_data:", apdu, apdulen);
 
531
  rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
 
532
  *buflen = ctbuflen;
 
533
 
 
534
  return rc? SW_HOST_CARD_IO_ERROR: 0;
 
535
}
 
536
 
 
537
 
 
538
 
 
539
/* Open a reader and return an internal handle for it.  PORT is a
 
540
   non-negative value with the port number of the reader. USB readers
 
541
   do have port numbers starting at 32769. */
 
542
static int
 
543
open_ct_reader (int port)
 
544
{
 
545
  int rc, reader;
 
546
 
 
547
  if (port < 0 || port > 0xffff)
 
548
    {
 
549
      log_error ("open_ct_reader: invalid port %d requested\n", port);
 
550
      return -1;
 
551
    }
 
552
  reader = new_reader_slot ();
 
553
  if (reader == -1)
 
554
    return reader;
 
555
  reader_table[reader].port = port;
 
556
 
 
557
  rc = CT_init (reader, (unsigned short)port);
 
558
  if (rc)
 
559
    {
 
560
      log_error ("apdu_open_ct_reader failed on port %d: %s\n",
 
561
                 port, ct_error_string (rc));
 
562
      reader_table[reader].used = 0;
 
563
      return -1;
 
564
    }
 
565
 
 
566
  /* Only try to activate the card. */
 
567
  rc = ct_activate_card (reader);
 
568
  if (rc)
 
569
    {
 
570
      reader_table[reader].atrlen = 0;
 
571
      rc = 0;
 
572
    }
 
573
 
 
574
  reader_table[reader].close_reader = close_ct_reader;
 
575
  reader_table[reader].reset_reader = reset_ct_reader;
 
576
  reader_table[reader].get_status_reader = ct_get_status;
 
577
  reader_table[reader].send_apdu_reader = ct_send_apdu;
 
578
  reader_table[reader].dump_status_reader = ct_dump_reader_status;
 
579
 
 
580
  dump_reader_status (reader);
 
581
  return reader;
 
582
}
 
583
 
 
584
 
 
585
#ifdef NEED_PCSC_WRAPPER
 
586
static int
 
587
writen (int fd, const void *buf, size_t nbytes)
 
588
{
 
589
  size_t nleft = nbytes;
 
590
  int nwritten;
 
591
 
 
592
/*   log_printhex (" writen:", buf, nbytes); */
 
593
 
 
594
  while (nleft > 0)
 
595
    {
 
596
#ifdef USE_GNU_PTH
 
597
      nwritten = pth_write (fd, buf, nleft);
 
598
#else
 
599
      nwritten = write (fd, buf, nleft);
 
600
#endif
 
601
      if (nwritten < 0 && errno == EINTR)
 
602
        continue;
 
603
      if (nwritten < 0)
 
604
        return -1;
 
605
      nleft -= nwritten;
 
606
      buf = (const char*)buf + nwritten;
 
607
    }
 
608
  return 0;
 
609
}
 
610
 
 
611
/* Read up to BUFLEN bytes from FD and return the number of bytes
 
612
   actually read in NREAD.  Returns -1 on error or 0 on success. */
 
613
static int
 
614
readn (int fd, void *buf, size_t buflen, size_t *nread)
 
615
{
 
616
  size_t nleft = buflen;
 
617
  int n;
 
618
/*   void *orig_buf = buf; */
 
619
 
 
620
  while (nleft > 0)
 
621
    {
 
622
#ifdef USE_GNU_PTH
 
623
      n = pth_read (fd, buf, nleft);
 
624
#else
 
625
      n = read (fd, buf, nleft);
 
626
#endif
 
627
      if (n < 0 && errno == EINTR) 
 
628
        continue;
 
629
      if (n < 0)
 
630
        return -1; /* read error. */
 
631
      if (!n)
 
632
        break; /* EOF */
 
633
      nleft -= n;
 
634
      buf = (char*)buf + n;
 
635
    }
 
636
  if (nread)
 
637
    *nread = buflen - nleft;
 
638
 
 
639
/*   log_printhex ("  readn:", orig_buf, *nread); */
 
640
    
 
641
  return 0;
 
642
}
 
643
#endif /*NEED_PCSC_WRAPPER*/
 
644
 
 
645
static const char *
 
646
pcsc_error_string (long err)
 
647
{
 
648
  const char *s;
 
649
 
 
650
  if (!err)
 
651
    return "okay";
 
652
  if ((err & 0x80100000) != 0x80100000)
 
653
    return "invalid PC/SC error code";
 
654
  err &= 0xffff;
 
655
  switch (err)
 
656
    {
 
657
    case 0x0002: s = "cancelled"; break;
 
658
    case 0x000e: s = "can't dispose"; break;
 
659
    case 0x0008: s = "insufficient buffer"; break;   
 
660
    case 0x0015: s = "invalid ATR"; break;
 
661
    case 0x0003: s = "invalid handle"; break;
 
662
    case 0x0004: s = "invalid parameter"; break; 
 
663
    case 0x0005: s = "invalid target"; break;
 
664
    case 0x0011: s = "invalid value"; break; 
 
665
    case 0x0006: s = "no memory"; break;  
 
666
    case 0x0013: s = "comm error"; break;      
 
667
    case 0x0001: s = "internal error"; break;     
 
668
    case 0x0014: s = "unknown error"; break; 
 
669
    case 0x0007: s = "waited too long"; break;  
 
670
    case 0x0009: s = "unknown reader"; break;
 
671
    case 0x000a: s = "timeout"; break; 
 
672
    case 0x000b: s = "sharing violation"; break;       
 
673
    case 0x000c: s = "no smartcard"; break;
 
674
    case 0x000d: s = "unknown card"; break;   
 
675
    case 0x000f: s = "proto mismatch"; break;          
 
676
    case 0x0010: s = "not ready"; break;               
 
677
    case 0x0012: s = "system cancelled"; break;        
 
678
    case 0x0016: s = "not transacted"; break;
 
679
    case 0x0017: s = "reader unavailable"; break; 
 
680
    case 0x0065: s = "unsupported card"; break;        
 
681
    case 0x0066: s = "unresponsive card"; break;       
 
682
    case 0x0067: s = "unpowered card"; break;          
 
683
    case 0x0068: s = "reset card"; break;              
 
684
    case 0x0069: s = "removed card"; break;            
 
685
    case 0x006a: s = "inserted card"; break;           
 
686
    case 0x001f: s = "unsupported feature"; break;     
 
687
    case 0x0019: s = "PCI too small"; break;           
 
688
    case 0x001a: s = "reader unsupported"; break;      
 
689
    case 0x001b: s = "duplicate reader"; break;        
 
690
    case 0x001c: s = "card unsupported"; break;        
 
691
    case 0x001d: s = "no service"; break;              
 
692
    case 0x001e: s = "service stopped"; break;      
 
693
    default:     s = "unknown PC/SC error code"; break;
 
694
    }
 
695
  return s;
 
696
}
 
697
 
 
698
/* 
 
699
       PC/SC Interface
 
700
 */
 
701
 
 
702
static void
 
703
dump_pcsc_reader_status (int slot)
 
704
{
 
705
  log_info ("reader slot %d: active protocol:", slot);
 
706
  if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
 
707
    log_printf (" T0");
 
708
  else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
 
709
    log_printf (" T1");
 
710
  else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
 
711
    log_printf (" raw");
 
712
  log_printf ("\n");
 
713
}
 
714
 
 
715
 
 
716
static int
 
717
reset_pcsc_reader (int slot)
 
718
{
 
719
#ifdef NEED_PCSC_WRAPPER
 
720
  long err;
 
721
  reader_table_t slotp;
 
722
  size_t len;
 
723
  int i, n;
 
724
  unsigned char msgbuf[9];
 
725
 
 
726
  slotp = reader_table + slot;
 
727
 
 
728
  if (slotp->pcsc.req_fd == -1 
 
729
      || slotp->pcsc.rsp_fd == -1 
 
730
      || slotp->pcsc.pid == (pid_t)(-1) )
 
731
    {
 
732
      log_error ("pcsc_get_status: pcsc-wrapper not running\n");
 
733
      return SW_HOST_CARD_IO_ERROR;
 
734
    }
 
735
 
 
736
  msgbuf[0] = 0x05; /* RESET command. */
 
737
  len = 0;
 
738
  msgbuf[1] = (len >> 24);
 
739
  msgbuf[2] = (len >> 16);
 
740
  msgbuf[3] = (len >>  8);
 
741
  msgbuf[4] = (len      );
 
742
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
743
    {
 
744
      log_error ("error sending PC/SC RESET request: %s\n",
 
745
                 strerror (errno));
 
746
      goto command_failed;
 
747
    }
 
748
 
 
749
  /* Read the response. */
 
750
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
751
    {
 
752
      log_error ("error receiving PC/SC RESET response: %s\n",
 
753
                 i? strerror (errno) : "premature EOF");
 
754
      goto command_failed;
 
755
    }
 
756
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
757
  if (msgbuf[0] != 0x81 || len < 4)
 
758
    {
 
759
      log_error ("invalid response header from PC/SC received\n");
 
760
      goto command_failed;
 
761
    }
 
762
  len -= 4; /* Already read the error code. */
 
763
  if (len > DIM (slotp->atr))
 
764
    {
 
765
      log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
 
766
      goto command_failed;
 
767
    }
 
768
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
769
  if (err)
 
770
    {
 
771
      log_error ("PC/SC RESET failed: %s\n", pcsc_error_string (err));
 
772
      goto command_failed;
 
773
    }
 
774
 
 
775
  /* The open fucntion may return a zero for the ATR length to
 
776
     indicate that no card is present.  */
 
777
  n = len;
 
778
  if (n)
 
779
    {
 
780
      if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
 
781
        {
 
782
          log_error ("error receiving PC/SC RESET response: %s\n",
 
783
                     i? strerror (errno) : "premature EOF");
 
784
          goto command_failed;
 
785
        }
 
786
    }
 
787
  slotp->atrlen = len;
 
788
 
 
789
  return 0;
 
790
 
 
791
 command_failed:
 
792
  close (slotp->pcsc.req_fd);
 
793
  close (slotp->pcsc.rsp_fd);
 
794
  slotp->pcsc.req_fd = -1;
 
795
  slotp->pcsc.rsp_fd = -1;
 
796
  kill (slotp->pcsc.pid, SIGTERM);
 
797
  slotp->pcsc.pid = (pid_t)(-1);
 
798
  slotp->used = 0;
 
799
  return -1;
 
800
 
 
801
#else /* !NEED_PCSC_WRAPPER */
 
802
  long err;
 
803
  char reader[250];
 
804
  unsigned long nreader, atrlen;
 
805
  unsigned long card_state, card_protocol;
 
806
 
 
807
  if (reader_table[slot].pcsc.card)
 
808
    {
 
809
      err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
 
810
      if (err)
 
811
        {
 
812
          log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
 
813
                     pcsc_error_string (err), err);
 
814
          return SW_HOST_CARD_IO_ERROR;
 
815
        }
 
816
      reader_table[slot].pcsc.card = 0;
 
817
    }
 
818
 
 
819
  err = pcsc_connect (reader_table[slot].pcsc.context,
 
820
                      reader_table[slot].rdrname,
 
821
                      PCSC_SHARE_EXCLUSIVE,
 
822
                      PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
 
823
                      &reader_table[slot].pcsc.card,
 
824
                      &reader_table[slot].pcsc.protocol);
 
825
  if (err)
 
826
    {
 
827
      log_error ("pcsc_connect failed: %s (0x%lx)\n",
 
828
                  pcsc_error_string (err), err);
 
829
      reader_table[slot].pcsc.card = 0;
 
830
      return SW_HOST_CARD_IO_ERROR;
 
831
    }      
 
832
 
 
833
  
 
834
  atrlen = 33;
 
835
  nreader = sizeof reader - 1;
 
836
  err = pcsc_status (reader_table[slot].pcsc.card,
 
837
                     reader, &nreader,
 
838
                     &card_state, &card_protocol,
 
839
                     reader_table[slot].atr, &atrlen);
 
840
  if (err)
 
841
    {
 
842
      log_error ("pcsc_status failed: %s (0x%lx)\n",
 
843
                  pcsc_error_string (err), err);
 
844
      reader_table[slot].atrlen = 0;
 
845
      return SW_HOST_CARD_IO_ERROR;
 
846
    }
 
847
  if (atrlen >= DIM (reader_table[0].atr))
 
848
    log_bug ("ATR returned by pcsc_status is too large\n");
 
849
  reader_table[slot].atrlen = atrlen;
 
850
 
 
851
  return 0;
 
852
#endif /* !NEED_PCSC_WRAPPER */
 
853
}
 
854
 
 
855
 
 
856
static int
 
857
pcsc_get_status (int slot, unsigned int *status)
 
858
{
 
859
#ifdef NEED_PCSC_WRAPPER
 
860
  long err;
 
861
  reader_table_t slotp;
 
862
  size_t len, full_len;
 
863
  int i, n;
 
864
  unsigned char msgbuf[9];
 
865
  unsigned char buffer[12];
 
866
 
 
867
  slotp = reader_table + slot;
 
868
 
 
869
  if (slotp->pcsc.req_fd == -1 
 
870
      || slotp->pcsc.rsp_fd == -1 
 
871
      || slotp->pcsc.pid == (pid_t)(-1) )
 
872
    {
 
873
      log_error ("pcsc_get_status: pcsc-wrapper not running\n");
 
874
      return SW_HOST_CARD_IO_ERROR;
 
875
    }
 
876
 
 
877
  msgbuf[0] = 0x04; /* STATUS command. */
 
878
  len = 0;
 
879
  msgbuf[1] = (len >> 24);
 
880
  msgbuf[2] = (len >> 16);
 
881
  msgbuf[3] = (len >>  8);
 
882
  msgbuf[4] = (len      );
 
883
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
884
    {
 
885
      log_error ("error sending PC/SC STATUS request: %s\n",
 
886
                 strerror (errno));
 
887
      goto command_failed;
 
888
    }
 
889
 
 
890
  /* Read the response. */
 
891
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
892
    {
 
893
      log_error ("error receiving PC/SC STATUS response: %s\n",
 
894
                 i? strerror (errno) : "premature EOF");
 
895
      goto command_failed;
 
896
    }
 
897
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
898
  if (msgbuf[0] != 0x81 || len < 4)
 
899
    {
 
900
      log_error ("invalid response header from PC/SC received\n");
 
901
      goto command_failed;
 
902
    }
 
903
  len -= 4; /* Already read the error code. */
 
904
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
905
  if (err)
 
906
    {
 
907
      log_error ("pcsc_status failed: %s (0x%lx)\n",
 
908
                 pcsc_error_string (err), err);
 
909
      return SW_HOST_CARD_IO_ERROR;
 
910
    }
 
911
 
 
912
  full_len = len;
 
913
  
 
914
  n = 8 < len ? 8 : len;
 
915
  if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != 8)
 
916
    {
 
917
      log_error ("error receiving PC/SC STATUS response: %s\n",
 
918
                 i? strerror (errno) : "premature EOF");
 
919
      goto command_failed;
 
920
    }
 
921
 
 
922
  full_len -= len;
 
923
  /* Newer versions of the wrapper might send more status bytes.
 
924
     Read them. */
 
925
  while (full_len)
 
926
    {
 
927
      unsigned char dummybuf[128];
 
928
 
 
929
      n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
 
930
      if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
 
931
        {
 
932
          log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
933
                     i? strerror (errno) : "premature EOF");
 
934
          goto command_failed;
 
935
        }
 
936
      full_len -= n;
 
937
    }
 
938
   
 
939
  /* We are lucky: The wrapper already returns the data in the
 
940
     required format. */
 
941
  *status = buffer[3];
 
942
 
 
943
  return 0;
 
944
 
 
945
 command_failed:
 
946
  close (slotp->pcsc.req_fd);
 
947
  close (slotp->pcsc.rsp_fd);
 
948
  slotp->pcsc.req_fd = -1;
 
949
  slotp->pcsc.rsp_fd = -1;
 
950
  kill (slotp->pcsc.pid, SIGTERM);
 
951
  slotp->pcsc.pid = (pid_t)(-1);
 
952
  slotp->used = 0;
 
953
  return -1;
 
954
 
 
955
#else /*!NEED_PCSC_WRAPPER*/
 
956
 
 
957
  long err;
 
958
  struct pcsc_readerstate_s rdrstates[1];
 
959
  
 
960
  memset (rdrstates, 0, sizeof *rdrstates);
 
961
  rdrstates[0].reader = reader_table[slot].rdrname;
 
962
  rdrstates[0].current_state = PCSC_STATE_UNAWARE;
 
963
  err = pcsc_get_status_change (reader_table[slot].pcsc.context,
 
964
                                0,
 
965
                                rdrstates, 1);
 
966
  if (err == 0x8010000a) /* Timeout.  */
 
967
    err = 0;
 
968
  if (err)
 
969
    {
 
970
      log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
 
971
                 pcsc_error_string (err), err);
 
972
      return SW_HOST_CARD_IO_ERROR;
 
973
    }
 
974
 
 
975
 
 
976
  /*   log_debug  */
 
977
  /*     ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
 
978
  /*      (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
 
979
  /*      (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
 
980
  /*      (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
 
981
  /*      (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
 
982
  /*      (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
 
983
  /*      (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
 
984
  /*      (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
 
985
  /*      (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
 
986
  /*      (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
 
987
  /*      (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
 
988
 
 
989
  *status = 0;
 
990
  if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
 
991
    *status |= 2;
 
992
  if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
 
993
    *status |= 4;
 
994
  /* We indicate a useful card if it is not in use by another
 
995
     application.  This is because we only use exclusive access
 
996
     mode.  */
 
997
  if ( (*status & 6) == 6
 
998
       && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
 
999
    *status |= 1;
 
1000
  
 
1001
  return 0; 
 
1002
#endif /*!NEED_PCSC_WRAPPER*/
 
1003
}
 
1004
 
 
1005
 
 
1006
/* Actually send the APDU of length APDULEN to SLOT and return a
 
1007
   maximum of *BUFLEN data in BUFFER, the actual returned size will be
 
1008
   set to BUFLEN.  Returns: CT API error code. */
 
1009
static int
 
1010
pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
1011
                unsigned char *buffer, size_t *buflen)
 
1012
{
 
1013
#ifdef NEED_PCSC_WRAPPER
 
1014
  long err;
 
1015
  reader_table_t slotp;
 
1016
  size_t len, full_len;
 
1017
  int i, n;
 
1018
  unsigned char msgbuf[9];
 
1019
 
 
1020
  if (!reader_table[slot].atrlen
 
1021
      && (err = reset_pcsc_reader (slot)))
 
1022
    return err;
 
1023
 
 
1024
  if (DBG_CARD_IO)
 
1025
    log_printhex ("  PCSC_data:", apdu, apdulen);
 
1026
 
 
1027
  slotp = reader_table + slot;
 
1028
 
 
1029
  if (slotp->pcsc.req_fd == -1 
 
1030
      || slotp->pcsc.rsp_fd == -1 
 
1031
      || slotp->pcsc.pid == (pid_t)(-1) )
 
1032
    {
 
1033
      log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
 
1034
      return SW_HOST_CARD_IO_ERROR;
 
1035
    }
 
1036
 
 
1037
  msgbuf[0] = 0x03; /* TRANSMIT command. */
 
1038
  len = apdulen;
 
1039
  msgbuf[1] = (len >> 24);
 
1040
  msgbuf[2] = (len >> 16);
 
1041
  msgbuf[3] = (len >>  8);
 
1042
  msgbuf[4] = (len      );
 
1043
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
 
1044
       || writen (slotp->pcsc.req_fd, apdu, len))
 
1045
    {
 
1046
      log_error ("error sending PC/SC TRANSMIT request: %s\n",
 
1047
                 strerror (errno));
 
1048
      goto command_failed;
 
1049
    }
 
1050
 
 
1051
  /* Read the response. */
 
1052
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1053
    {
 
1054
      log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1055
                 i? strerror (errno) : "premature EOF");
 
1056
      goto command_failed;
 
1057
    }
 
1058
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1059
  if (msgbuf[0] != 0x81 || len < 4)
 
1060
    {
 
1061
      log_error ("invalid response header from PC/SC received\n");
 
1062
      goto command_failed;
 
1063
    }
 
1064
  len -= 4; /* Already read the error code. */
 
1065
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1066
  if (err)
 
1067
    {
 
1068
      log_error ("pcsc_transmit failed: %s (0x%lx)\n",
 
1069
                 pcsc_error_string (err), err);
 
1070
      return SW_HOST_CARD_IO_ERROR;
 
1071
    }
 
1072
 
 
1073
   full_len = len;
 
1074
   
 
1075
   n = *buflen < len ? *buflen : len;
 
1076
   if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
 
1077
     {
 
1078
       log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1079
                  i? strerror (errno) : "premature EOF");
 
1080
       goto command_failed;
 
1081
     }
 
1082
   *buflen = n;
 
1083
 
 
1084
   full_len -= len;
 
1085
   if (full_len)
 
1086
     {
 
1087
       log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
 
1088
       err = SW_HOST_INV_VALUE;
 
1089
     }
 
1090
   /* We need to read any rest of the response, to keep the
 
1091
      protocol runnng. */
 
1092
   while (full_len)
 
1093
     {
 
1094
       unsigned char dummybuf[128];
 
1095
 
 
1096
       n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
 
1097
       if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
 
1098
         {
 
1099
           log_error ("error receiving PC/SC TRANSMIT response: %s\n",
 
1100
                      i? strerror (errno) : "premature EOF");
 
1101
           goto command_failed;
 
1102
         }
 
1103
       full_len -= n;
 
1104
     }
 
1105
 
 
1106
   return err;
 
1107
 
 
1108
 command_failed:
 
1109
  close (slotp->pcsc.req_fd);
 
1110
  close (slotp->pcsc.rsp_fd);
 
1111
  slotp->pcsc.req_fd = -1;
 
1112
  slotp->pcsc.rsp_fd = -1;
 
1113
  kill (slotp->pcsc.pid, SIGTERM);
 
1114
  slotp->pcsc.pid = (pid_t)(-1);
 
1115
  slotp->used = 0;
 
1116
  return -1;
 
1117
 
 
1118
#else /*!NEED_PCSC_WRAPPER*/
 
1119
 
 
1120
  long err;
 
1121
  struct pcsc_io_request_s send_pci;
 
1122
  unsigned long recv_len;
 
1123
  
 
1124
  if (!reader_table[slot].atrlen
 
1125
      && (err = reset_pcsc_reader (slot)))
 
1126
    return err;
 
1127
 
 
1128
  if (DBG_CARD_IO)
 
1129
    log_printhex ("  PCSC_data:", apdu, apdulen);
 
1130
 
 
1131
  if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
 
1132
      send_pci.protocol = PCSC_PROTOCOL_T1;
 
1133
  else
 
1134
      send_pci.protocol = PCSC_PROTOCOL_T0;
 
1135
  send_pci.pci_len = sizeof send_pci;
 
1136
  recv_len = *buflen;
 
1137
  err = pcsc_transmit (reader_table[slot].pcsc.card,
 
1138
                       &send_pci, apdu, apdulen,
 
1139
                       NULL, buffer, &recv_len);
 
1140
  *buflen = recv_len;
 
1141
  if (err)
 
1142
    log_error ("pcsc_transmit failed: %s (0x%lx)\n",
 
1143
               pcsc_error_string (err), err);
 
1144
  
 
1145
  return err? SW_HOST_CARD_IO_ERROR:0; 
 
1146
#endif /*!NEED_PCSC_WRAPPER*/
 
1147
}
 
1148
 
 
1149
 
 
1150
static int
 
1151
close_pcsc_reader (int slot)
 
1152
{
 
1153
#ifdef NEED_PCSC_WRAPPER
 
1154
  long err;
 
1155
  reader_table_t slotp;
 
1156
  size_t len;
 
1157
  int i;
 
1158
  unsigned char msgbuf[9];
 
1159
 
 
1160
  slotp = reader_table + slot;
 
1161
 
 
1162
  if (slotp->pcsc.req_fd == -1 
 
1163
      || slotp->pcsc.rsp_fd == -1 
 
1164
      || slotp->pcsc.pid == (pid_t)(-1) )
 
1165
    {
 
1166
      log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
 
1167
      return 0;
 
1168
    }
 
1169
 
 
1170
  msgbuf[0] = 0x02; /* CLOSE command. */
 
1171
  len = 0;
 
1172
  msgbuf[1] = (len >> 24);
 
1173
  msgbuf[2] = (len >> 16);
 
1174
  msgbuf[3] = (len >>  8);
 
1175
  msgbuf[4] = (len      );
 
1176
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
 
1177
    {
 
1178
      log_error ("error sending PC/SC CLOSE request: %s\n",
 
1179
                 strerror (errno));
 
1180
      goto command_failed;
 
1181
    }
 
1182
 
 
1183
  /* Read the response. */
 
1184
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1185
    {
 
1186
      log_error ("error receiving PC/SC CLOSE response: %s\n",
 
1187
                 i? strerror (errno) : "premature EOF");
 
1188
      goto command_failed;
 
1189
    }
 
1190
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1191
  if (msgbuf[0] != 0x81 || len < 4)
 
1192
    {
 
1193
      log_error ("invalid response header from PC/SC received\n");
 
1194
      goto command_failed;
 
1195
    }
 
1196
  len -= 4; /* Already read the error code. */
 
1197
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1198
  if (err)
 
1199
    log_error ("pcsc_close failed: %s (0x%lx)\n",
 
1200
               pcsc_error_string (err), err);
 
1201
  
 
1202
  /* We will the wrapper in any case - errors are merely
 
1203
     informational. */
 
1204
  
 
1205
 command_failed:
 
1206
  close (slotp->pcsc.req_fd);
 
1207
  close (slotp->pcsc.rsp_fd);
 
1208
  slotp->pcsc.req_fd = -1;
 
1209
  slotp->pcsc.rsp_fd = -1;
 
1210
  kill (slotp->pcsc.pid, SIGTERM);
 
1211
  slotp->pcsc.pid = (pid_t)(-1);
 
1212
  slotp->used = 0;
 
1213
  return 0;
 
1214
 
 
1215
#else /*!NEED_PCSC_WRAPPER*/
 
1216
 
 
1217
  pcsc_release_context (reader_table[slot].pcsc.context);
 
1218
  xfree (reader_table[slot].rdrname);
 
1219
  reader_table[slot].rdrname = NULL;
 
1220
  reader_table[slot].used = 0;
 
1221
  return 0;
 
1222
#endif /*!NEED_PCSC_WRAPPER*/
 
1223
}
 
1224
 
 
1225
static int
 
1226
open_pcsc_reader (const char *portstr)
 
1227
{
 
1228
#ifdef NEED_PCSC_WRAPPER
 
1229
/* Open the PC/SC reader using the pcsc_wrapper program.  This is
 
1230
   needed to cope with different thread models and other peculiarities
 
1231
   of libpcsclite. */
 
1232
  int slot;
 
1233
  reader_table_t slotp;
 
1234
  int fd, rp[2], wp[2];
 
1235
  int n, i;
 
1236
  pid_t pid;
 
1237
  size_t len;
 
1238
  unsigned char msgbuf[9];
 
1239
  int err;
 
1240
 
 
1241
  slot = new_reader_slot ();
 
1242
  if (slot == -1)
 
1243
    return -1;
 
1244
  slotp = reader_table + slot;
 
1245
 
 
1246
  /* Fire up the pcsc wrapper.  We don't use any fork/exec code from
 
1247
     the common directy but implement it direclty so that this file
 
1248
     may still be source copied. */
 
1249
  
 
1250
  if (pipe (rp) == -1)
 
1251
    {
 
1252
      log_error ("error creating a pipe: %s\n", strerror (errno));
 
1253
      slotp->used = 0;
 
1254
      return -1;
 
1255
    }
 
1256
  if (pipe (wp) == -1)
 
1257
    {
 
1258
      log_error ("error creating a pipe: %s\n", strerror (errno));
 
1259
      close (rp[0]);
 
1260
      close (rp[1]);
 
1261
      slotp->used = 0;
 
1262
      return -1;
 
1263
    }
 
1264
      
 
1265
  pid = fork ();
 
1266
  if (pid == -1)
 
1267
    {
 
1268
      log_error ("error forking process: %s\n", strerror (errno));
 
1269
      close (rp[0]);
 
1270
      close (rp[1]);
 
1271
      close (wp[0]);
 
1272
      close (wp[1]);
 
1273
      slotp->used = 0;
 
1274
      return -1;
 
1275
    }
 
1276
  slotp->pcsc.pid = pid;
 
1277
 
 
1278
  if (!pid)
 
1279
    { /*
 
1280
         === Child ===
 
1281
       */
 
1282
 
 
1283
      /* Double fork. */
 
1284
      pid = fork ();
 
1285
      if (pid == -1)
 
1286
        _exit (31); 
 
1287
      if (pid)
 
1288
        _exit (0); /* Immediate exit this parent, so that the child
 
1289
                      gets cleaned up by the init process. */
 
1290
 
 
1291
      /* Connect our pipes. */
 
1292
      if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
 
1293
        log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
 
1294
      if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
 
1295
        log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
 
1296
      
 
1297
      /* Send stderr to the bit bucket. */
 
1298
      fd = open ("/dev/null", O_WRONLY);
 
1299
      if (fd == -1)
 
1300
        log_fatal ("can't open `/dev/null': %s", strerror (errno));
 
1301
      if (fd != 2 && dup2 (fd, 2) == -1)
 
1302
        log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
 
1303
 
 
1304
      /* Close all other files. */
 
1305
      n = sysconf (_SC_OPEN_MAX);
 
1306
      if (n < 0)
 
1307
        n = MAX_OPEN_FDS;
 
1308
      for (i=3; i < n; i++)
 
1309
        close(i);
 
1310
      errno = 0;
 
1311
 
 
1312
      execl (GNUPG_LIBDIR "/pcsc-wrapper",
 
1313
             "pcsc-wrapper",
 
1314
             "--",
 
1315
             "1", /* API version */
 
1316
             opt.pcsc_driver, /* Name of the PC/SC library. */
 
1317
              NULL);
 
1318
      _exit (31);
 
1319
    }
 
1320
 
 
1321
  /* 
 
1322
     === Parent ===
 
1323
   */
 
1324
  close (wp[0]);
 
1325
  close (rp[1]);
 
1326
  slotp->pcsc.req_fd = wp[1];
 
1327
  slotp->pcsc.rsp_fd = rp[0];
 
1328
 
 
1329
  /* Wait for the intermediate child to terminate. */
 
1330
#ifdef USE_GNU_PTH
 
1331
#define WAIT pth_waitpid 
 
1332
#else
 
1333
#define WAIT waitpid 
 
1334
#endif
 
1335
  while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
 
1336
    ;
 
1337
#undef X
 
1338
 
 
1339
  /* Now send the open request. */
 
1340
  msgbuf[0] = 0x01; /* OPEN command. */
 
1341
  len = portstr? strlen (portstr):0;
 
1342
  msgbuf[1] = (len >> 24);
 
1343
  msgbuf[2] = (len >> 16);
 
1344
  msgbuf[3] = (len >>  8);
 
1345
  msgbuf[4] = (len      );
 
1346
  if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
 
1347
       || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
 
1348
    {
 
1349
      log_error ("error sending PC/SC OPEN request: %s\n",
 
1350
                 strerror (errno));
 
1351
      goto command_failed;
 
1352
    }
 
1353
  /* Read the response. */
 
1354
  if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
 
1355
    {
 
1356
      log_error ("error receiving PC/SC OPEN response: %s\n",
 
1357
                 i? strerror (errno) : "premature EOF");
 
1358
      goto command_failed;
 
1359
    }
 
1360
  len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
 
1361
  if (msgbuf[0] != 0x81 || len < 4)
 
1362
    {
 
1363
      log_error ("invalid response header from PC/SC received\n");
 
1364
      goto command_failed;
 
1365
    }
 
1366
  len -= 4; /* Already read the error code. */
 
1367
  if (len > DIM (slotp->atr))
 
1368
    {
 
1369
      log_error ("PC/SC returned a too large ATR (len=%x)\n", len);
 
1370
      goto command_failed;
 
1371
    }
 
1372
  err = (msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8];
 
1373
  if (err)
 
1374
    {
 
1375
      log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
 
1376
      goto command_failed;
 
1377
    }
 
1378
 
 
1379
  slotp->last_status = 0;
 
1380
 
 
1381
  /* The open fucntion may return a zero for the ATR length to
 
1382
     indicate that no card is present.  */
 
1383
  n = len;
 
1384
  if (n)
 
1385
    {
 
1386
      if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
 
1387
        {
 
1388
          log_error ("error receiving PC/SC OPEN response: %s\n",
 
1389
                     i? strerror (errno) : "premature EOF");
 
1390
          goto command_failed;
 
1391
        }
 
1392
      /* If we got to here we know that a card is present
 
1393
         and usable.  Thus remember this.  */
 
1394
      slotp->last_status = (1|2|4| 0x8000);
 
1395
    }
 
1396
  slotp->atrlen = len;
 
1397
 
 
1398
  reader_table[slot].close_reader = close_pcsc_reader;
 
1399
  reader_table[slot].reset_reader = reset_pcsc_reader;
 
1400
  reader_table[slot].get_status_reader = pcsc_get_status;
 
1401
  reader_table[slot].send_apdu_reader = pcsc_send_apdu;
 
1402
  reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
 
1403
 
 
1404
  dump_reader_status (slot); 
 
1405
  return slot;
 
1406
 
 
1407
 command_failed:
 
1408
  close (slotp->pcsc.req_fd);
 
1409
  close (slotp->pcsc.rsp_fd);
 
1410
  slotp->pcsc.req_fd = -1;
 
1411
  slotp->pcsc.rsp_fd = -1;
 
1412
  kill (slotp->pcsc.pid, SIGTERM);
 
1413
  slotp->pcsc.pid = (pid_t)(-1);
 
1414
  slotp->used = 0;
 
1415
  return -1;
 
1416
#else /*!NEED_PCSC_WRAPPER */
 
1417
  long err;
 
1418
  int slot;
 
1419
  char *list = NULL;
 
1420
  unsigned long nreader, listlen, atrlen;
 
1421
  char *p;
 
1422
  unsigned long card_state, card_protocol;
 
1423
 
 
1424
  slot = new_reader_slot ();
 
1425
  if (slot == -1)
 
1426
    return -1;
 
1427
 
 
1428
  err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
 
1429
                                &reader_table[slot].pcsc.context);
 
1430
  if (err)
 
1431
    {
 
1432
      log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
 
1433
                 pcsc_error_string (err), err);
 
1434
      reader_table[slot].used = 0;
 
1435
      return -1;
 
1436
    }
 
1437
  
 
1438
  err = pcsc_list_readers (reader_table[slot].pcsc.context,
 
1439
                           NULL, NULL, &nreader);
 
1440
  if (!err)
 
1441
    {
 
1442
      list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
 
1443
      if (!list)
 
1444
        {
 
1445
          log_error ("error allocating memory for reader list\n");
 
1446
          pcsc_release_context (reader_table[slot].pcsc.context);
 
1447
          reader_table[slot].used = 0;
 
1448
          return -1;
 
1449
        }
 
1450
      err = pcsc_list_readers (reader_table[slot].pcsc.context,
 
1451
                               NULL, list, &nreader);
 
1452
    }
 
1453
  if (err)
 
1454
    {
 
1455
      log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
 
1456
                 pcsc_error_string (err), err);
 
1457
      pcsc_release_context (reader_table[slot].pcsc.context);
 
1458
      reader_table[slot].used = 0;
 
1459
      xfree (list);
 
1460
      return -1;
 
1461
    }
 
1462
 
 
1463
  listlen = nreader;
 
1464
  p = list;
 
1465
  while (nreader)
 
1466
    {
 
1467
      if (!*p && !p[1])
 
1468
        break;
 
1469
      if (*p)
 
1470
        log_info ("detected reader `%s'\n", p);
 
1471
      if (nreader < (strlen (p)+1))
 
1472
        {
 
1473
          log_error ("invalid response from pcsc_list_readers\n");
 
1474
          break;
 
1475
        }
 
1476
      nreader -= strlen (p)+1;
 
1477
      p += strlen (p) + 1;
 
1478
    }
 
1479
 
 
1480
  reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
 
1481
  if (!reader_table[slot].rdrname)
 
1482
    {
 
1483
      log_error ("error allocating memory for reader name\n");
 
1484
      pcsc_release_context (reader_table[slot].pcsc.context);
 
1485
      reader_table[slot].used = 0;
 
1486
      return -1;
 
1487
    }
 
1488
  strcpy (reader_table[slot].rdrname, portstr? portstr : list);
 
1489
  xfree (list);
 
1490
 
 
1491
  err = pcsc_connect (reader_table[slot].pcsc.context,
 
1492
                      reader_table[slot].rdrname,
 
1493
                      PCSC_SHARE_EXCLUSIVE,
 
1494
                      PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
 
1495
                      &reader_table[slot].pcsc.card,
 
1496
                      &reader_table[slot].pcsc.protocol);
 
1497
  if (err == 0x8010000c) /* No smartcard.  */
 
1498
    reader_table[slot].pcsc.card = 0;
 
1499
  else if (err)
 
1500
    {
 
1501
      log_error ("pcsc_connect failed: %s (0x%lx)\n",
 
1502
                  pcsc_error_string (err), err);
 
1503
      pcsc_release_context (reader_table[slot].pcsc.context);
 
1504
      xfree (reader_table[slot].rdrname);
 
1505
      reader_table[slot].rdrname = NULL;
 
1506
      reader_table[slot].used = 0;
 
1507
      xfree (list);
 
1508
      return -1;
 
1509
    }      
 
1510
 
 
1511
  reader_table[slot].atrlen = 0;
 
1512
  reader_table[slot].last_status = 0;
 
1513
  if (!err)
 
1514
    {
 
1515
      char reader[250];
 
1516
      unsigned long readerlen;
 
1517
 
 
1518
      atrlen = 32;
 
1519
      readerlen = sizeof reader -1 ;
 
1520
      err = pcsc_status (reader_table[slot].pcsc.card,
 
1521
                         reader, &readerlen,
 
1522
                         &card_state, &card_protocol,
 
1523
                         reader_table[slot].atr, &atrlen);
 
1524
      if (err)
 
1525
        log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
 
1526
                   pcsc_error_string (err), err, readerlen);
 
1527
      else
 
1528
        {
 
1529
          if (atrlen >= DIM (reader_table[0].atr))
 
1530
            log_bug ("ATR returned by pcsc_status is too large\n");
 
1531
          reader_table[slot].atrlen = atrlen;
 
1532
          /* If we got to here we know that a card is present
 
1533
             and usable.  Thus remember this.  */
 
1534
          reader_table[slot].last_status = (1|2|4| 0x8000);
 
1535
        }
 
1536
    }
 
1537
 
 
1538
  reader_table[slot].close_reader = close_pcsc_reader;
 
1539
  reader_table[slot].reset_reader = reset_pcsc_reader;
 
1540
  reader_table[slot].get_status_reader = pcsc_get_status;
 
1541
  reader_table[slot].send_apdu_reader = pcsc_send_apdu;
 
1542
  reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
 
1543
 
 
1544
/*   log_debug ("state    from pcsc_status: 0x%lx\n", card_state); */
 
1545
/*   log_debug ("protocol from pcsc_status: 0x%lx\n", card_protocol); */
 
1546
 
 
1547
  dump_reader_status (slot); 
 
1548
  return slot;
 
1549
#endif /*!NEED_PCSC_WRAPPER */
 
1550
}
 
1551
 
 
1552
 
 
1553
 
 
1554
 
 
1555
#ifdef HAVE_LIBUSB
 
1556
/* 
 
1557
     Internal CCID driver interface.
 
1558
 */
 
1559
 
 
1560
 
 
1561
static void
 
1562
dump_ccid_reader_status (int slot)
 
1563
{
 
1564
  log_info ("reader slot %d: using ccid driver\n", slot);
 
1565
}
 
1566
 
 
1567
static int
 
1568
close_ccid_reader (int slot)
 
1569
{
 
1570
  ccid_close_reader (reader_table[slot].ccid.handle);
 
1571
  reader_table[slot].used = 0;
 
1572
  return 0;
 
1573
}                       
 
1574
  
 
1575
 
 
1576
static int
 
1577
shutdown_ccid_reader (int slot)
 
1578
{
 
1579
  ccid_shutdown_reader (reader_table[slot].ccid.handle);
 
1580
  return 0;
 
1581
}                       
 
1582
  
 
1583
 
 
1584
static int
 
1585
reset_ccid_reader (int slot)
 
1586
{
 
1587
  int err;
 
1588
  reader_table_t slotp = reader_table + slot;
 
1589
  unsigned char atr[33];
 
1590
  size_t atrlen;
 
1591
 
 
1592
  err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
 
1593
  if (err)
 
1594
    return err;
 
1595
  /* If the reset was successful, update the ATR. */
 
1596
  assert (sizeof slotp->atr >= sizeof atr);
 
1597
  slotp->atrlen = atrlen;
 
1598
  memcpy (slotp->atr, atr, atrlen);
 
1599
  dump_reader_status (slot); 
 
1600
  return 0;
 
1601
}                       
 
1602
  
 
1603
 
 
1604
static int
 
1605
get_status_ccid (int slot, unsigned int *status)
 
1606
{
 
1607
  int rc;
 
1608
  int bits;
 
1609
 
 
1610
  rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
 
1611
  if (rc)
 
1612
    return -1;
 
1613
 
 
1614
  if (bits == 0)
 
1615
    *status = 1|2|4;
 
1616
  else if (bits == 1)
 
1617
    *status = 2;
 
1618
  else 
 
1619
    *status = 0;
 
1620
 
 
1621
  return 0;
 
1622
}
 
1623
 
 
1624
 
 
1625
/* Actually send the APDU of length APDULEN to SLOT and return a
 
1626
   maximum of *BUFLEN data in BUFFER, the actual returned size will be
 
1627
   set to BUFLEN.  Returns: Internal CCID driver error code. */
 
1628
static int
 
1629
send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
 
1630
                unsigned char *buffer, size_t *buflen)
 
1631
{
 
1632
  long err;
 
1633
  size_t maxbuflen;
 
1634
 
 
1635
  /* If we don't have an ATR, we need to reset the reader first. */
 
1636
  if (!reader_table[slot].atrlen
 
1637
      && (err = reset_ccid_reader (slot)))
 
1638
    return err;
 
1639
 
 
1640
  if (DBG_CARD_IO)
 
1641
    log_printhex ("  APDU_data:", apdu, apdulen);
 
1642
 
 
1643
  maxbuflen = *buflen;
 
1644
  err = ccid_transceive (reader_table[slot].ccid.handle,
 
1645
                         apdu, apdulen,
 
1646
                         buffer, maxbuflen, buflen);
 
1647
  if (err)
 
1648
    log_error ("ccid_transceive failed: (0x%lx)\n",
 
1649
               err);
 
1650
  
 
1651
  return err; 
 
1652
}
 
1653
 
 
1654
/* Open the reader and try to read an ATR.  */
 
1655
static int
 
1656
open_ccid_reader (const char *portstr)
 
1657
{
 
1658
  int err;
 
1659
  int slot;
 
1660
  reader_table_t slotp;
 
1661
 
 
1662
  slot = new_reader_slot ();
 
1663
  if (slot == -1)
 
1664
    return -1;
 
1665
  slotp = reader_table + slot;
 
1666
 
 
1667
  err = ccid_open_reader (&slotp->ccid.handle, portstr);
 
1668
  if (err)
 
1669
    {
 
1670
      slotp->used = 0;
 
1671
      return -1;
 
1672
    }
 
1673
 
 
1674
  err = ccid_get_atr (slotp->ccid.handle,
 
1675
                      slotp->atr, sizeof slotp->atr, &slotp->atrlen);
 
1676
  if (err)
 
1677
    {
 
1678
      slotp->atrlen = 0;
 
1679
      err = 0;
 
1680
    }
 
1681
  else
 
1682
    {
 
1683
      /* If we got to here we know that a card is present
 
1684
         and usable.  Thus remember this.  */
 
1685
      reader_table[slot].last_status = (1|2|4| 0x8000);
 
1686
    }
 
1687
 
 
1688
  reader_table[slot].close_reader = close_ccid_reader;
 
1689
  reader_table[slot].shutdown_reader = shutdown_ccid_reader;
 
1690
  reader_table[slot].reset_reader = reset_ccid_reader;
 
1691
  reader_table[slot].get_status_reader = get_status_ccid;
 
1692
  reader_table[slot].send_apdu_reader = send_apdu_ccid;
 
1693
  reader_table[slot].dump_status_reader = dump_ccid_reader_status;
 
1694
 
 
1695
  dump_reader_status (slot); 
 
1696
  return slot;
 
1697
}
 
1698
 
 
1699
 
 
1700
 
 
1701
#endif /* HAVE_LIBUSB */
 
1702
 
 
1703
 
 
1704
 
 
1705
#ifdef HAVE_OPENSC
 
1706
/* 
 
1707
     OpenSC Interface.
 
1708
 
 
1709
     This uses the OpenSC primitives to send APDUs.  We need this
 
1710
     because we can't mix OpenSC and native (i.e. ctAPI or PC/SC)
 
1711
     access to a card for resource conflict reasons.
 
1712
 */
 
1713
 
 
1714
 
 
1715
static int
 
1716
close_osc_reader (int slot)
 
1717
{
 
1718
  /* FIXME: Implement. */
 
1719
  reader_table[slot].used = 0;
 
1720
  return 0;
 
1721
}
 
1722
 
 
1723
static int
 
1724
reset_osc_reader (int slot)
 
1725
{
 
1726
  return SW_HOST_NOT_SUPPORTED;
 
1727
}
 
1728
 
 
1729
 
 
1730
static int
 
1731
osc_get_status (int slot, unsigned int *status)
 
1732
{
 
1733
  return SW_HOST_NOT_SUPPORTED;
 
1734
}
 
1735
 
 
1736
 
 
1737
/* Actually send the APDU of length APDULEN to SLOT and return a
 
1738
   maximum of *BUFLEN data in BUFFER, the actual returned size will be
 
1739
   set to BUFLEN.  Returns: OpenSC error code. */
 
1740
static int
 
1741
osc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
1742
                unsigned char *buffer, size_t *buflen)
 
1743
{
 
1744
  long err;
 
1745
  struct sc_apdu a;
 
1746
  unsigned char data[SC_MAX_APDU_BUFFER_SIZE];
 
1747
  unsigned char result[SC_MAX_APDU_BUFFER_SIZE];
 
1748
 
 
1749
  if (DBG_CARD_IO)
 
1750
    log_printhex ("  APDU_data:", apdu, apdulen);
 
1751
 
 
1752
  if (apdulen < 4)
 
1753
    {
 
1754
      log_error ("osc_send_apdu: APDU is too short\n");
 
1755
      return SW_HOST_INV_VALUE;
 
1756
    }
 
1757
 
 
1758
  memset(&a, 0, sizeof a);
 
1759
  a.cla = *apdu++;
 
1760
  a.ins = *apdu++;
 
1761
  a.p1 = *apdu++;
 
1762
  a.p2 = *apdu++;
 
1763
  apdulen -= 4;
 
1764
 
 
1765
  if (!apdulen)
 
1766
    a.cse = SC_APDU_CASE_1;
 
1767
  else if (apdulen == 1) 
 
1768
    {
 
1769
      a.le = *apdu? *apdu : 256;
 
1770
      apdu++; apdulen--;
 
1771
      a.cse = SC_APDU_CASE_2_SHORT;
 
1772
    }
 
1773
  else
 
1774
    {
 
1775
      a.lc = *apdu++; apdulen--;
 
1776
      if (apdulen < a.lc)
 
1777
        {
 
1778
          log_error ("osc_send_apdu: APDU shorter than specified in Lc\n");
 
1779
          return SW_HOST_INV_VALUE;
 
1780
 
 
1781
        }
 
1782
      memcpy(data, apdu, a.lc);
 
1783
      apdu += a.lc; apdulen -= a.lc;
 
1784
 
 
1785
      a.data = data;
 
1786
      a.datalen = a.lc;
 
1787
      
 
1788
      if (!apdulen)
 
1789
        a.cse = SC_APDU_CASE_3_SHORT;
 
1790
      else
 
1791
        {
 
1792
          a.le = *apdu? *apdu : 256;
 
1793
          apdu++; apdulen--;
 
1794
          if (apdulen)
 
1795
            {
 
1796
              log_error ("osc_send_apdu: APDU larger than specified\n");
 
1797
              return SW_HOST_INV_VALUE;
 
1798
            }
 
1799
          a.cse = SC_APDU_CASE_4_SHORT;
 
1800
        }
 
1801
    }
 
1802
 
 
1803
  a.resp = result;
 
1804
  a.resplen = DIM(result);
 
1805
 
 
1806
  err = sc_transmit_apdu (reader_table[slot].osc.scard, &a);
 
1807
  if (err)
 
1808
    {
 
1809
      log_error ("sc_apdu_transmit failed: %s\n", sc_strerror (err));
 
1810
      return SW_HOST_CARD_IO_ERROR;
 
1811
    }
 
1812
 
 
1813
  if (*buflen < 2 || a.resplen > *buflen - 2)
 
1814
    {
 
1815
      log_error ("osc_send_apdu: provided buffer too short to store result\n");
 
1816
      return SW_HOST_INV_VALUE;
 
1817
    }
 
1818
  memcpy (buffer, a.resp, a.resplen);
 
1819
  buffer[a.resplen] = a.sw1;
 
1820
  buffer[a.resplen+1] = a.sw2;
 
1821
  *buflen = a.resplen + 2;
 
1822
  return 0;
 
1823
}
 
1824
 
 
1825
static int
 
1826
open_osc_reader (int portno)
 
1827
{
 
1828
  int err;
 
1829
  int slot;
 
1830
  reader_table_t slotp;
 
1831
 
 
1832
  slot = new_reader_slot ();
 
1833
  if (slot == -1)
 
1834
    return -1;
 
1835
  slotp = reader_table + slot;
 
1836
 
 
1837
  err = sc_establish_context (&slotp->osc.ctx, "scdaemon");
 
1838
  if (err)
 
1839
    {
 
1840
      log_error ("failed to establish SC context: %s\n", sc_strerror (err));
 
1841
      slotp->used = 0;
 
1842
      return -1;
 
1843
    }
 
1844
  if (portno < 0 || portno >= slotp->osc.ctx->reader_count)
 
1845
    {
 
1846
      log_error ("no card reader available\n");
 
1847
      sc_release_context (slotp->osc.ctx);
 
1848
      slotp->used = 0;
 
1849
      return -1;
 
1850
    }
 
1851
 
 
1852
  /* Redirect to our logging facility. */
 
1853
  slotp->osc.ctx->error_file = log_get_stream ();
 
1854
  slotp->osc.ctx->debug = opt.debug_sc;
 
1855
  slotp->osc.ctx->debug_file = log_get_stream ();
 
1856
 
 
1857
  if (sc_detect_card_presence (slotp->osc.ctx->reader[portno], 0) != 1)
 
1858
    {
 
1859
      log_error ("no card present\n");
 
1860
      sc_release_context (slotp->osc.ctx);
 
1861
      slotp->used = 0;
 
1862
      return -1;
 
1863
    }
 
1864
  
 
1865
  /* We want the standard ISO driver. */
 
1866
  /*FIXME: OpenSC does not like "iso7816", so we use EMV for now. */
 
1867
  err = sc_set_card_driver(slotp->osc.ctx, "emv");
 
1868
  if (err)
 
1869
    {
 
1870
      log_error ("failed to select the iso7816 driver: %s\n",
 
1871
                 sc_strerror (err));
 
1872
      sc_release_context (slotp->osc.ctx);
 
1873
      slotp->used = 0;
 
1874
      return -1;
 
1875
    }
 
1876
 
 
1877
  /* Now connect the card and hope that OpenSC won't try to be too
 
1878
     smart. */
 
1879
  err = sc_connect_card (slotp->osc.ctx->reader[portno], 0,
 
1880
                         &slotp->osc.scard);
 
1881
  if (err)
 
1882
    {
 
1883
      log_error ("failed to connect card in reader %d: %s\n",
 
1884
                 portno, sc_strerror (err));
 
1885
      sc_release_context (slotp->osc.ctx);
 
1886
      slotp->used = 0;
 
1887
      return -1;
 
1888
    }
 
1889
  if (opt.verbose)
 
1890
    log_info ("connected to card in opensc reader %d using driver `%s'\n",
 
1891
              portno, slotp->osc.scard->driver->name);
 
1892
 
 
1893
  err = sc_lock (slotp->osc.scard);
 
1894
  if (err)
 
1895
    {
 
1896
      log_error ("can't lock card in reader %d: %s\n",
 
1897
                 portno, sc_strerror (err));
 
1898
      sc_disconnect_card (slotp->osc.scard, 0);
 
1899
      sc_release_context (slotp->osc.ctx);
 
1900
      slotp->used = 0;
 
1901
      return -1;
 
1902
    }
 
1903
 
 
1904
  if (slotp->osc.scard->atr_len >= DIM (slotp->atr))
 
1905
    log_bug ("ATR returned by opensc is too large\n");
 
1906
  slotp->atrlen = slotp->osc.scard->atr_len;
 
1907
  memcpy (slotp->atr, slotp->osc.scard->atr, slotp->atrlen);
 
1908
 
 
1909
  reader_table[slot].close_reader = close_osc_reader;
 
1910
  reader_table[slot].reset_reader = reset_osc_reader;
 
1911
  reader_table[slot].get_status_reader = osc_get_status;
 
1912
  reader_table[slot].send_apdu_reader = osc_send_apdu;
 
1913
  reader_table[slot].dump_status_reader = NULL;
 
1914
 
 
1915
  dump_reader_status (slot); 
 
1916
  return slot;
 
1917
}
 
1918
 
 
1919
#endif /* HAVE_OPENSC */
 
1920
 
 
1921
 
 
1922
 
 
1923
#ifdef USE_G10CODE_RAPDU
 
1924
/* 
 
1925
     The Remote APDU Interface.
 
1926
 
 
1927
     This uses the Remote APDU protocol to contact a reader.
 
1928
 
 
1929
     The port number is actually an index into the list of ports as
 
1930
     returned via the protocol.
 
1931
 */
 
1932
 
 
1933
 
 
1934
static int
 
1935
rapdu_status_to_sw (int status)
 
1936
{
 
1937
  int rc;
 
1938
 
 
1939
  switch (status)
 
1940
    {
 
1941
    case RAPDU_STATUS_SUCCESS:  rc = 0; break;
 
1942
 
 
1943
    case RAPDU_STATUS_INVCMD:  
 
1944
    case RAPDU_STATUS_INVPROT:  
 
1945
    case RAPDU_STATUS_INVSEQ:  
 
1946
    case RAPDU_STATUS_INVCOOKIE:
 
1947
    case RAPDU_STATUS_INVREADER:  rc = SW_HOST_INV_VALUE;  break;
 
1948
 
 
1949
    case RAPDU_STATUS_TIMEOUT:  rc = SW_HOST_CARD_IO_ERROR; break;
 
1950
    case RAPDU_STATUS_CARDIO:   rc = SW_HOST_CARD_IO_ERROR; break;
 
1951
    case RAPDU_STATUS_NOCARD:   rc = SW_HOST_NO_CARD; break;
 
1952
    case RAPDU_STATUS_CARDCHG:  rc = SW_HOST_NO_CARD; break;
 
1953
    case RAPDU_STATUS_BUSY:     rc = SW_HOST_BUSY; break;
 
1954
    case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
 
1955
 
 
1956
    default: rc = SW_HOST_GENERAL_ERROR; break;
 
1957
    }
 
1958
 
 
1959
  return rc;
 
1960
}
 
1961
 
 
1962
 
 
1963
 
 
1964
static int
 
1965
close_rapdu_reader (int slot)
 
1966
{
 
1967
  rapdu_release (reader_table[slot].rapdu.handle);
 
1968
  reader_table[slot].used = 0;
 
1969
  return 0;
 
1970
}
 
1971
 
 
1972
 
 
1973
static int
 
1974
reset_rapdu_reader (int slot)
 
1975
{
 
1976
  int err;
 
1977
  reader_table_t slotp;
 
1978
  rapdu_msg_t msg = NULL;
 
1979
 
 
1980
  slotp = reader_table + slot;
 
1981
 
 
1982
  err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
 
1983
  if (err)
 
1984
    {
 
1985
      log_error ("sending rapdu command RESET failed: %s\n",
 
1986
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
1987
      rapdu_msg_release (msg);
 
1988
      return rapdu_status_to_sw (err);
 
1989
    }
 
1990
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
1991
  if (err)
 
1992
    {
 
1993
      log_error ("receiving rapdu message failed: %s\n",
 
1994
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
1995
      rapdu_msg_release (msg);
 
1996
      return rapdu_status_to_sw (err);
 
1997
    }
 
1998
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
1999
    {
 
2000
      int sw = rapdu_status_to_sw (msg->cmd);
 
2001
      log_error ("rapdu command RESET failed: %s\n",
 
2002
                 rapdu_strerror (msg->cmd));
 
2003
      rapdu_msg_release (msg);
 
2004
      return sw;
 
2005
    }
 
2006
  if (msg->datalen >= DIM (slotp->atr))
 
2007
    {
 
2008
      log_error ("ATR returned by the RAPDU layer is too large\n");
 
2009
      rapdu_msg_release (msg);
 
2010
      return SW_HOST_INV_VALUE; 
 
2011
    }
 
2012
  slotp->atrlen = msg->datalen;
 
2013
  memcpy (slotp->atr, msg->data, msg->datalen);
 
2014
 
 
2015
  rapdu_msg_release (msg);
 
2016
  return 0;
 
2017
}
 
2018
 
 
2019
 
 
2020
static int
 
2021
my_rapdu_get_status (int slot, unsigned int *status)
 
2022
{
 
2023
  int err;
 
2024
  reader_table_t slotp;
 
2025
  rapdu_msg_t msg = NULL;
 
2026
  int oldslot;
 
2027
 
 
2028
  slotp = reader_table + slot;
 
2029
 
 
2030
  oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
 
2031
  err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
 
2032
  rapdu_set_reader (slotp->rapdu.handle, oldslot);
 
2033
  if (err)
 
2034
    {
 
2035
      log_error ("sending rapdu command GET_STATUS failed: %s\n",
 
2036
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2037
      return rapdu_status_to_sw (err);
 
2038
    }
 
2039
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2040
  if (err)
 
2041
    {
 
2042
      log_error ("receiving rapdu message failed: %s\n",
 
2043
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2044
      rapdu_msg_release (msg);
 
2045
      return rapdu_status_to_sw (err);
 
2046
    }
 
2047
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2048
    {
 
2049
      int sw = rapdu_status_to_sw (msg->cmd);
 
2050
      log_error ("rapdu command GET_STATUS failed: %s\n",
 
2051
                 rapdu_strerror (msg->cmd));
 
2052
      rapdu_msg_release (msg);
 
2053
      return sw;
 
2054
    }
 
2055
  *status = msg->data[0];
 
2056
 
 
2057
  rapdu_msg_release (msg);
 
2058
  return 0;
 
2059
}
 
2060
 
 
2061
 
 
2062
/* Actually send the APDU of length APDULEN to SLOT and return a
 
2063
   maximum of *BUFLEN data in BUFFER, the actual returned size will be
 
2064
   set to BUFLEN.  Returns: OpenSC error code. */
 
2065
static int
 
2066
my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
2067
                    unsigned char *buffer, size_t *buflen)
 
2068
{
 
2069
  int err;
 
2070
  reader_table_t slotp;
 
2071
  rapdu_msg_t msg = NULL;
 
2072
  size_t maxlen = *buflen;
 
2073
 
 
2074
  slotp = reader_table + slot;
 
2075
 
 
2076
  *buflen = 0;
 
2077
  if (DBG_CARD_IO)
 
2078
    log_printhex ("  APDU_data:", apdu, apdulen);
 
2079
 
 
2080
  if (apdulen < 4)
 
2081
    {
 
2082
      log_error ("rapdu_send_apdu: APDU is too short\n");
 
2083
      return SW_HOST_INV_VALUE;
 
2084
    }
 
2085
 
 
2086
  err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
 
2087
  if (err)
 
2088
    {
 
2089
      log_error ("sending rapdu command APDU failed: %s\n",
 
2090
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2091
      rapdu_msg_release (msg);
 
2092
      return rapdu_status_to_sw (err);
 
2093
    }
 
2094
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2095
  if (err)
 
2096
    {
 
2097
      log_error ("receiving rapdu message failed: %s\n",
 
2098
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2099
      rapdu_msg_release (msg);
 
2100
      return rapdu_status_to_sw (err);
 
2101
    }
 
2102
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2103
    {
 
2104
      int sw = rapdu_status_to_sw (msg->cmd);
 
2105
      log_error ("rapdu command APDU failed: %s\n",
 
2106
                 rapdu_strerror (msg->cmd));
 
2107
      rapdu_msg_release (msg);
 
2108
      return sw;
 
2109
    }
 
2110
  
 
2111
  if (msg->datalen > maxlen)
 
2112
    {
 
2113
      log_error ("rapdu response apdu too large\n");
 
2114
      rapdu_msg_release (msg);
 
2115
      return SW_HOST_INV_VALUE; 
 
2116
    }
 
2117
 
 
2118
  *buflen = msg->datalen;
 
2119
  memcpy (buffer, msg->data, msg->datalen);
 
2120
 
 
2121
  rapdu_msg_release (msg);
 
2122
  return 0;
 
2123
}
 
2124
 
 
2125
static int
 
2126
open_rapdu_reader (int portno,
 
2127
                   const unsigned char *cookie, size_t length,
 
2128
                   int (*readfnc) (void *opaque,
 
2129
                                   void *buffer, size_t size),
 
2130
                   void *readfnc_value,
 
2131
                   int (*writefnc) (void *opaque,
 
2132
                                    const void *buffer, size_t size),
 
2133
                   void *writefnc_value,
 
2134
                   void (*closefnc) (void *opaque),
 
2135
                   void *closefnc_value)
 
2136
{
 
2137
  int err;
 
2138
  int slot;
 
2139
  reader_table_t slotp;
 
2140
  rapdu_msg_t msg = NULL;
 
2141
 
 
2142
  slot = new_reader_slot ();
 
2143
  if (slot == -1)
 
2144
    return -1;
 
2145
  slotp = reader_table + slot;
 
2146
 
 
2147
  slotp->rapdu.handle = rapdu_new ();
 
2148
  if (!slotp->rapdu.handle)
 
2149
    {
 
2150
      slotp->used = 0;
 
2151
      return -1;
 
2152
    }
 
2153
 
 
2154
 
 
2155
  rapdu_set_iofunc (slotp->rapdu.handle,
 
2156
                    readfnc, readfnc_value,
 
2157
                    writefnc, writefnc_value,
 
2158
                    closefnc, closefnc_value);
 
2159
  rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
 
2160
 
 
2161
  /* First try to get the current ATR, but if the card is inactive
 
2162
     issue a reset instead.  */
 
2163
  err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
 
2164
  if (err == RAPDU_STATUS_NEEDRESET)
 
2165
    err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
 
2166
  if (err)
 
2167
    {
 
2168
      log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
 
2169
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2170
      goto failure;
 
2171
    }
 
2172
  err = rapdu_read_msg (slotp->rapdu.handle, &msg);
 
2173
  if (err)
 
2174
    {
 
2175
      log_info ("receiving rapdu message failed: %s\n",
 
2176
                err < 0 ? strerror (errno): rapdu_strerror (err));
 
2177
      goto failure;
 
2178
    }
 
2179
  if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
 
2180
    {
 
2181
      log_info ("rapdu command GET ATR failed: %s\n",
 
2182
                 rapdu_strerror (msg->cmd));
 
2183
      goto failure;
 
2184
    }
 
2185
  if (msg->datalen >= DIM (slotp->atr))
 
2186
    {
 
2187
      log_error ("ATR returned by the RAPDU layer is too large\n");
 
2188
      goto failure;
 
2189
    }
 
2190
  slotp->atrlen = msg->datalen;
 
2191
  memcpy (slotp->atr, msg->data, msg->datalen);
 
2192
 
 
2193
  reader_table[slot].close_reader = close_rapdu_reader;
 
2194
  reader_table[slot].reset_reader = reset_rapdu_reader;
 
2195
  reader_table[slot].get_status_reader = my_rapdu_get_status;
 
2196
  reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
 
2197
  reader_table[slot].dump_status_reader = NULL;
 
2198
 
 
2199
  dump_reader_status (slot); 
 
2200
  rapdu_msg_release (msg);
 
2201
  return slot;
 
2202
 
 
2203
 failure:      
 
2204
  rapdu_msg_release (msg);
 
2205
  rapdu_release (slotp->rapdu.handle);
 
2206
  slotp->used = 0;
 
2207
  return -1;
 
2208
}
 
2209
 
 
2210
#endif /*USE_G10CODE_RAPDU*/
 
2211
 
 
2212
 
 
2213
 
 
2214
/* 
 
2215
       Driver Access
 
2216
 */
 
2217
 
 
2218
 
 
2219
static int
 
2220
lock_slot (int slot)
 
2221
{
 
2222
#ifdef USE_GNU_PTH
 
2223
  if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
 
2224
    {
 
2225
      log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
 
2226
      return SW_HOST_LOCKING_FAILED;
 
2227
    }
 
2228
#endif /*USE_GNU_PTH*/
 
2229
  return 0;
 
2230
}
 
2231
 
 
2232
static int
 
2233
trylock_slot (int slot)
 
2234
{
 
2235
#ifdef USE_GNU_PTH
 
2236
  if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
 
2237
    {
 
2238
      if (errno == EBUSY)
 
2239
        return SW_HOST_BUSY;
 
2240
      log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
 
2241
      return SW_HOST_LOCKING_FAILED;
 
2242
    }
 
2243
#endif /*USE_GNU_PTH*/
 
2244
  return 0;
 
2245
}
 
2246
 
 
2247
static void
 
2248
unlock_slot (int slot)
 
2249
{
 
2250
#ifdef USE_GNU_PTH
 
2251
  if (!pth_mutex_release (&reader_table[slot].lock))
 
2252
    log_error ("failed to release apdu lock: %s\n", strerror (errno));
 
2253
#endif /*USE_GNU_PTH*/
 
2254
}
 
2255
 
 
2256
 
 
2257
/* Open the reader and return an internal slot number or -1 on
 
2258
   error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
 
2259
   the first USB reader.  For PC/SC the first listed reader).  If
 
2260
   OpenSC support is compiled in, we first try to use OpenSC. */
 
2261
int
 
2262
apdu_open_reader (const char *portstr)
 
2263
{
 
2264
  static int pcsc_api_loaded, ct_api_loaded;
 
2265
 
 
2266
#ifdef HAVE_LIBUSB
 
2267
  if (!opt.disable_ccid)
 
2268
    {
 
2269
      int slot, i;
 
2270
      const char *s;
 
2271
 
 
2272
      slot = open_ccid_reader (portstr);
 
2273
      if (slot != -1)
 
2274
        return slot; /* got one */
 
2275
 
 
2276
      /* If a CCID reader specification has been given, the user does
 
2277
         not want a fallback to other drivers. */
 
2278
      if (portstr)
 
2279
        for (s=portstr, i=0; *s; s++)
 
2280
          if (*s == ':' && (++i == 3))
 
2281
            return -1;
 
2282
    }
 
2283
 
 
2284
#endif /* HAVE_LIBUSB */
 
2285
 
 
2286
#ifdef HAVE_OPENSC
 
2287
  if (!opt.disable_opensc)
 
2288
    {
 
2289
      int port = portstr? atoi (portstr) : 0;
 
2290
 
 
2291
      return open_osc_reader (port);
 
2292
    }
 
2293
#endif /* HAVE_OPENSC */  
 
2294
 
 
2295
 
 
2296
  if (opt.ctapi_driver && *opt.ctapi_driver)
 
2297
    {
 
2298
      int port = portstr? atoi (portstr) : 32768;
 
2299
 
 
2300
      if (!ct_api_loaded)
 
2301
        {
 
2302
          void *handle;
 
2303
          
 
2304
          handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
 
2305
          if (!handle)
 
2306
            {
 
2307
              log_error ("apdu_open_reader: failed to open driver: %s\n",
 
2308
                         dlerror ());
 
2309
              return -1;
 
2310
            }
 
2311
          CT_init = dlsym (handle, "CT_init");
 
2312
          CT_data = dlsym (handle, "CT_data");
 
2313
          CT_close = dlsym (handle, "CT_close");
 
2314
          if (!CT_init || !CT_data || !CT_close)
 
2315
            {
 
2316
              log_error ("apdu_open_reader: invalid CT-API driver\n");
 
2317
              dlclose (handle);
 
2318
              return -1;
 
2319
            }
 
2320
          ct_api_loaded = 1;
 
2321
        }
 
2322
      return open_ct_reader (port);
 
2323
    }
 
2324
 
 
2325
  
 
2326
  /* No ctAPI configured, so lets try the PC/SC API */
 
2327
  if (!pcsc_api_loaded)
 
2328
    {
 
2329
#ifndef NEED_PCSC_WRAPPER
 
2330
      void *handle;
 
2331
 
 
2332
      handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
 
2333
      if (!handle)
 
2334
        {
 
2335
          log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
 
2336
                     opt.pcsc_driver, dlerror ());
 
2337
          return -1;
 
2338
        }
 
2339
 
 
2340
      pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
 
2341
      pcsc_release_context   = dlsym (handle, "SCardReleaseContext");
 
2342
      pcsc_list_readers      = dlsym (handle, "SCardListReaders");
 
2343
#ifdef _WIN32
 
2344
      if (!pcsc_list_readers)
 
2345
        pcsc_list_readers    = dlsym (handle, "SCardListReadersA");
 
2346
#endif
 
2347
      pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
 
2348
#ifdef _WIN32
 
2349
      if (!pcsc_get_status_change)
 
2350
        pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
 
2351
#endif
 
2352
      pcsc_connect           = dlsym (handle, "SCardConnect");
 
2353
#ifdef _WIN32
 
2354
      if (!pcsc_connect)
 
2355
        pcsc_connect         = dlsym (handle, "SCardConnectA");
 
2356
#endif
 
2357
      pcsc_reconnect         = dlsym (handle, "SCardReconnect");
 
2358
#ifdef _WIN32
 
2359
      if (!pcsc_reconnect)
 
2360
        pcsc_reconnect       = dlsym (handle, "SCardReconnectA");
 
2361
#endif
 
2362
      pcsc_disconnect        = dlsym (handle, "SCardDisconnect");
 
2363
      pcsc_status            = dlsym (handle, "SCardStatus");
 
2364
#ifdef _WIN32
 
2365
      if (!pcsc_status)
 
2366
        pcsc_status          = dlsym (handle, "SCardStatusA");
 
2367
#endif
 
2368
      pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
 
2369
      pcsc_end_transaction   = dlsym (handle, "SCardEndTransaction");
 
2370
      pcsc_transmit          = dlsym (handle, "SCardTransmit");
 
2371
      pcsc_set_timeout       = dlsym (handle, "SCardSetTimeout");
 
2372
 
 
2373
      if (!pcsc_establish_context
 
2374
          || !pcsc_release_context  
 
2375
          || !pcsc_list_readers     
 
2376
          || !pcsc_get_status_change
 
2377
          || !pcsc_connect          
 
2378
          || !pcsc_reconnect
 
2379
          || !pcsc_disconnect
 
2380
          || !pcsc_status
 
2381
          || !pcsc_begin_transaction
 
2382
          || !pcsc_end_transaction
 
2383
          || !pcsc_transmit         
 
2384
          /* || !pcsc_set_timeout */)
 
2385
        {
 
2386
          /* Note that set_timeout is currently not used and also not
 
2387
             available under Windows. */
 
2388
          log_error ("apdu_open_reader: invalid PC/SC driver "
 
2389
                     "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
 
2390
                     !!pcsc_establish_context,
 
2391
                     !!pcsc_release_context,  
 
2392
                     !!pcsc_list_readers,     
 
2393
                     !!pcsc_get_status_change,     
 
2394
                     !!pcsc_connect,          
 
2395
                     !!pcsc_reconnect,          
 
2396
                     !!pcsc_disconnect,
 
2397
                     !!pcsc_status,
 
2398
                     !!pcsc_begin_transaction,
 
2399
                     !!pcsc_end_transaction,
 
2400
                     !!pcsc_transmit,         
 
2401
                     !!pcsc_set_timeout );
 
2402
          dlclose (handle);
 
2403
          return -1;
 
2404
        }
 
2405
#endif /*!NEED_PCSC_WRAPPER*/  
 
2406
      pcsc_api_loaded = 1;
 
2407
    }
 
2408
 
 
2409
  return open_pcsc_reader (portstr);
 
2410
}
 
2411
 
 
2412
 
 
2413
/* Open an remote reader and return an internal slot number or -1 on
 
2414
   error. This function is an alternative to apdu_open_reader and used
 
2415
   with remote readers only.  Note that the supplied CLOSEFNC will
 
2416
   only be called once and the slot will not be valid afther this.
 
2417
 
 
2418
   If PORTSTR is NULL we default to the first availabe port.
 
2419
*/  
 
2420
int
 
2421
apdu_open_remote_reader (const char *portstr,
 
2422
                         const unsigned char *cookie, size_t length,
 
2423
                         int (*readfnc) (void *opaque,
 
2424
                                         void *buffer, size_t size),
 
2425
                         void *readfnc_value,
 
2426
                         int (*writefnc) (void *opaque,
 
2427
                                          const void *buffer, size_t size),
 
2428
                         void *writefnc_value,
 
2429
                         void (*closefnc) (void *opaque),
 
2430
                         void *closefnc_value)
 
2431
{
 
2432
#ifdef USE_G10CODE_RAPDU
 
2433
  return open_rapdu_reader (portstr? atoi (portstr) : 0,
 
2434
                            cookie, length,
 
2435
                            readfnc, readfnc_value,
 
2436
                            writefnc, writefnc_value,
 
2437
                            closefnc, closefnc_value);
 
2438
#else
 
2439
#ifdef _WIN32 
 
2440
  errno = ENOENT;
 
2441
#else
 
2442
  errno = ENOSYS;
 
2443
#endif
 
2444
  return -1;
 
2445
#endif
 
2446
}
 
2447
 
 
2448
 
 
2449
int
 
2450
apdu_close_reader (int slot)
 
2451
{
 
2452
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2453
    return SW_HOST_NO_DRIVER;
 
2454
  if (reader_table[slot].close_reader)
 
2455
    return reader_table[slot].close_reader (slot);
 
2456
  return SW_HOST_NOT_SUPPORTED;
 
2457
}
 
2458
 
 
2459
/* Shutdown a reader; that is basically the same as a close but keeps
 
2460
   the handle ready for later use. A apdu_reset_header should be used
 
2461
   to get it active again. */
 
2462
int
 
2463
apdu_shutdown_reader (int slot)
 
2464
{
 
2465
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2466
    return SW_HOST_NO_DRIVER;
 
2467
  if (reader_table[slot].shutdown_reader)
 
2468
    return reader_table[slot].shutdown_reader (slot);
 
2469
  return SW_HOST_NOT_SUPPORTED;
 
2470
}
 
2471
 
 
2472
/* Enumerate all readers and return information on whether this reader
 
2473
   is in use.  The caller should start with SLOT set to 0 and
 
2474
   increment it with each call until an error is returned. */
 
2475
int
 
2476
apdu_enum_reader (int slot, int *used)
 
2477
{
 
2478
  if (slot < 0 || slot >= MAX_READER)
 
2479
    return SW_HOST_NO_DRIVER;
 
2480
  *used = reader_table[slot].used;
 
2481
  return 0;
 
2482
}
 
2483
 
 
2484
/* Do a reset for the card in reader at SLOT. */
 
2485
int
 
2486
apdu_reset (int slot)
 
2487
{
 
2488
  int sw;
 
2489
 
 
2490
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2491
    return SW_HOST_NO_DRIVER;
 
2492
  
 
2493
  if ((sw = lock_slot (slot)))
 
2494
    return sw;
 
2495
 
 
2496
  reader_table[slot].last_status = 0;
 
2497
  if (reader_table[slot].reset_reader)
 
2498
    sw = reader_table[slot].reset_reader (slot);
 
2499
 
 
2500
  if (!sw)
 
2501
    {
 
2502
      /* If we got to here we know that a card is present
 
2503
         and usable.  Thus remember this.  */
 
2504
      reader_table[slot].last_status = (1|2|4| 0x8000);
 
2505
    }
 
2506
 
 
2507
  unlock_slot (slot);
 
2508
  return sw;
 
2509
}
 
2510
 
 
2511
 
 
2512
/* Activate a card if it has not yet been done.  This is a kind of
 
2513
   reset-if-required.  It is useful to test for presence of a card
 
2514
   before issuing a bunch of apdu commands.  It does not wait on a
 
2515
   locked card. */
 
2516
int
 
2517
apdu_activate (int slot)
 
2518
{
 
2519
  int sw;
 
2520
  unsigned int s;
 
2521
 
 
2522
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2523
    return SW_HOST_NO_DRIVER;
 
2524
  
 
2525
  if ((sw = trylock_slot (slot)))
 
2526
    return sw;
 
2527
 
 
2528
  if (reader_table[slot].get_status_reader)
 
2529
    sw = reader_table[slot].get_status_reader (slot, &s);
 
2530
 
 
2531
  if (!sw)
 
2532
    {
 
2533
      if (!(s & 2))  /* Card not present.  */
 
2534
        sw = SW_HOST_NO_CARD;
 
2535
      else if ( ((s & 2) && !(s & 4))
 
2536
                || !reader_table[slot].atrlen )
 
2537
        {
 
2538
          /* We don't have an ATR or a card is present though inactive:
 
2539
             do a reset now. */
 
2540
          if (reader_table[slot].reset_reader)
 
2541
            {
 
2542
              reader_table[slot].last_status = 0;
 
2543
              sw = reader_table[slot].reset_reader (slot);
 
2544
              if (!sw)
 
2545
                {
 
2546
                  /* If we got to here we know that a card is present
 
2547
                     and usable.  Thus remember this.  */
 
2548
                  reader_table[slot].last_status = (1|2|4| 0x8000);
 
2549
                }
 
2550
            }
 
2551
        }
 
2552
    }
 
2553
  
 
2554
  unlock_slot (slot);
 
2555
  return sw;
 
2556
}
 
2557
 
 
2558
  
 
2559
 
 
2560
unsigned char *
 
2561
apdu_get_atr (int slot, size_t *atrlen)
 
2562
{
 
2563
  char *buf;
 
2564
 
 
2565
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2566
    return NULL;
 
2567
  
 
2568
  buf = xtrymalloc (reader_table[slot].atrlen);
 
2569
  if (!buf)
 
2570
    return NULL;
 
2571
  memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
 
2572
  *atrlen = reader_table[slot].atrlen;
 
2573
  return buf;
 
2574
}
 
2575
 
 
2576
 
 
2577
    
 
2578
/* Retrieve the status for SLOT. The function does only wait for the
 
2579
   card to become available if HANG is set to true. On success the
 
2580
   bits in STATUS will be set to
 
2581
 
 
2582
     bit 0 = card present and usable
 
2583
     bit 1 = card present
 
2584
     bit 2 = card active
 
2585
     bit 3 = card access locked [not yet implemented]
 
2586
 
 
2587
   For must application, testing bit 0 is sufficient.
 
2588
 
 
2589
   CHANGED will receive the value of the counter tracking the number
 
2590
   of card insertions.  This value may be used to detect a card
 
2591
   change.
 
2592
*/
 
2593
int
 
2594
apdu_get_status (int slot, int hang,
 
2595
                 unsigned int *status, unsigned int *changed)
 
2596
{
 
2597
  int sw;
 
2598
  unsigned int s;
 
2599
 
 
2600
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2601
    return SW_HOST_NO_DRIVER;
 
2602
 
 
2603
  if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
 
2604
    return sw;
 
2605
 
 
2606
  if (reader_table[slot].get_status_reader)
 
2607
    sw = reader_table[slot].get_status_reader (slot, &s);
 
2608
 
 
2609
  unlock_slot (slot);
 
2610
 
 
2611
  if (sw)
 
2612
    {
 
2613
      reader_table[slot].last_status = 0;
 
2614
      return sw;
 
2615
    }
 
2616
 
 
2617
  /* Keep track of changes.  We use one extra bit to test whether we
 
2618
     have checked the status at least once. */
 
2619
  if ( s != (reader_table[slot].last_status & 0x07ff)
 
2620
       || !reader_table[slot].last_status )
 
2621
    {
 
2622
      reader_table[slot].change_counter++;
 
2623
      /* Make sure that the ATR is invalid so that a reset will be by
 
2624
         activate.  */
 
2625
      reader_table[slot].atrlen = 0;
 
2626
    }
 
2627
  reader_table[slot].last_status = (s | 0x8000);
 
2628
 
 
2629
  if (status)
 
2630
    *status = s;
 
2631
  if (changed)
 
2632
    *changed = reader_table[slot].change_counter;
 
2633
  return 0;
 
2634
}
 
2635
 
 
2636
 
 
2637
/* Dispatcher for the actual send_apdu function. Note, that this
 
2638
   function should be called in locked state. */
 
2639
static int
 
2640
send_apdu (int slot, unsigned char *apdu, size_t apdulen,
 
2641
           unsigned char *buffer, size_t *buflen)
 
2642
{
 
2643
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2644
    return SW_HOST_NO_DRIVER;
 
2645
 
 
2646
  if (reader_table[slot].send_apdu_reader)
 
2647
    return reader_table[slot].send_apdu_reader (slot,
 
2648
                                                apdu, apdulen,
 
2649
                                                buffer, buflen);
 
2650
  else
 
2651
    return SW_HOST_NOT_SUPPORTED;
 
2652
}
 
2653
 
 
2654
/* Send an APDU to the card in SLOT.  The APDU is created from all
 
2655
   given parameters: CLASS, INS, P0, P1, LC, DATA, LE.  A value of -1
 
2656
   for LC won't sent this field and the data field; in this case DATA
 
2657
   must also be passed as NULL.  The return value is the status word
 
2658
   or -1 for an invalid SLOT or other non card related error.  If
 
2659
   RETBUF is not NULL, it will receive an allocated buffer with the
 
2660
   returned data.  The length of that data will be put into
 
2661
   *RETBUFLEN.  The caller is reponsible for releasing the buffer even
 
2662
   in case of errors.  */
 
2663
int 
 
2664
apdu_send_le(int slot, int class, int ins, int p0, int p1,
 
2665
             int lc, const char *data, int le,
 
2666
             unsigned char **retbuf, size_t *retbuflen)
 
2667
{
 
2668
#define RESULTLEN 256
 
2669
  unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
 
2670
                                         the driver. */
 
2671
  size_t resultlen;
 
2672
  unsigned char apdu[5+256+1];
 
2673
  size_t apdulen;
 
2674
  int sw;
 
2675
  long rc; /* we need a long here due to PC/SC. */
 
2676
 
 
2677
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2678
    return SW_HOST_NO_DRIVER;
 
2679
 
 
2680
  if (DBG_CARD_IO)
 
2681
    log_debug ("send apdu: c=%02X i=%02X p0=%02X p1=%02X lc=%d le=%d\n",
 
2682
               class, ins, p0, p1, lc, le);
 
2683
 
 
2684
  if (lc != -1 && (lc > 255 || lc < 0))
 
2685
    return SW_WRONG_LENGTH; 
 
2686
  if (le != -1 && (le > 256 || le < 1))
 
2687
    return SW_WRONG_LENGTH; 
 
2688
  if ((!data && lc != -1) || (data && lc == -1))
 
2689
    return SW_HOST_INV_VALUE;
 
2690
 
 
2691
  if ((sw = lock_slot (slot)))
 
2692
    return sw;
 
2693
 
 
2694
  apdulen = 0;
 
2695
  apdu[apdulen++] = class;
 
2696
  apdu[apdulen++] = ins;
 
2697
  apdu[apdulen++] = p0;
 
2698
  apdu[apdulen++] = p1;
 
2699
  if (lc != -1)
 
2700
    {
 
2701
      apdu[apdulen++] = lc;
 
2702
      memcpy (apdu+apdulen, data, lc);
 
2703
      apdulen += lc;
 
2704
    }
 
2705
  if (le != -1)
 
2706
    apdu[apdulen++] = le; /* Truncation is okay becuase 0 means 256. */
 
2707
  assert (sizeof (apdu) >= apdulen);
 
2708
  /* As safeguard don't pass any garbage from the stack to the driver. */
 
2709
  memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
 
2710
  resultlen = RESULTLEN;
 
2711
  rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
 
2712
  if (rc || resultlen < 2)
 
2713
    {
 
2714
      log_error ("apdu_send_simple(%d) failed: %s\n",
 
2715
                 slot, apdu_strerror (rc));
 
2716
      unlock_slot (slot);
 
2717
      return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2718
    }
 
2719
  sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2720
  /* store away the returned data but strip the statusword. */
 
2721
  resultlen -= 2;
 
2722
  if (DBG_CARD_IO)
 
2723
    {
 
2724
      log_debug (" response: sw=%04X  datalen=%d\n", sw, resultlen);
 
2725
      if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
 
2726
        log_printhex ("     dump: ", result, resultlen);
 
2727
    }
 
2728
 
 
2729
  if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
 
2730
    {
 
2731
      if (retbuf)
 
2732
        {
 
2733
          *retbuf = xtrymalloc (resultlen? resultlen : 1);
 
2734
          if (!*retbuf)
 
2735
            {
 
2736
              unlock_slot (slot);
 
2737
              return SW_HOST_OUT_OF_CORE;
 
2738
            }
 
2739
          *retbuflen = resultlen;
 
2740
          memcpy (*retbuf, result, resultlen);
 
2741
        }
 
2742
    }
 
2743
  else if ((sw & 0xff00) == SW_MORE_DATA)
 
2744
    {
 
2745
      unsigned char *p = NULL, *tmp;
 
2746
      size_t bufsize = 4096;
 
2747
 
 
2748
      /* It is likely that we need to return much more data, so we
 
2749
         start off with a large buffer. */
 
2750
      if (retbuf)
 
2751
        {
 
2752
          *retbuf = p = xtrymalloc (bufsize);
 
2753
          if (!*retbuf)
 
2754
            {
 
2755
              unlock_slot (slot);
 
2756
              return SW_HOST_OUT_OF_CORE;
 
2757
            }
 
2758
          assert (resultlen < bufsize);
 
2759
          memcpy (p, result, resultlen);
 
2760
          p += resultlen;
 
2761
        }
 
2762
 
 
2763
      do
 
2764
        {
 
2765
          int len = (sw & 0x00ff);
 
2766
          
 
2767
          if (DBG_CARD_IO)
 
2768
            log_debug ("apdu_send_simple(%d): %d more bytes available\n",
 
2769
                       slot, len);
 
2770
          apdulen = 0;
 
2771
          apdu[apdulen++] = class;
 
2772
          apdu[apdulen++] = 0xC0;
 
2773
          apdu[apdulen++] = 0;
 
2774
          apdu[apdulen++] = 0;
 
2775
          apdu[apdulen++] = len; 
 
2776
          memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
 
2777
          resultlen = RESULTLEN;
 
2778
          rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
 
2779
          if (rc || resultlen < 2)
 
2780
            {
 
2781
              log_error ("apdu_send_simple(%d) for get response failed: %s\n",
 
2782
                         slot, apdu_strerror (rc));
 
2783
              unlock_slot (slot);
 
2784
              return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2785
            }
 
2786
          sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2787
          resultlen -= 2;
 
2788
          if (DBG_CARD_IO)
 
2789
            {
 
2790
              log_debug ("     more: sw=%04X  datalen=%d\n", sw, resultlen);
 
2791
              if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
 
2792
                log_printhex ("     dump: ", result, resultlen);
 
2793
            }
 
2794
 
 
2795
          if ((sw & 0xff00) == SW_MORE_DATA
 
2796
              || sw == SW_SUCCESS
 
2797
              || sw == SW_EOF_REACHED )
 
2798
            {
 
2799
              if (retbuf && resultlen)
 
2800
                {
 
2801
                  if (p - *retbuf + resultlen > bufsize)
 
2802
                    {
 
2803
                      bufsize += resultlen > 4096? resultlen: 4096;
 
2804
                      tmp = xtryrealloc (*retbuf, bufsize);
 
2805
                      if (!tmp)
 
2806
                        {
 
2807
                          unlock_slot (slot);
 
2808
                          return SW_HOST_OUT_OF_CORE;
 
2809
                        }
 
2810
                      p = tmp + (p - *retbuf);
 
2811
                      *retbuf = tmp;
 
2812
                    }
 
2813
                  memcpy (p, result, resultlen);
 
2814
                  p += resultlen;
 
2815
                }
 
2816
            }
 
2817
          else
 
2818
            log_info ("apdu_send_simple(%d) "
 
2819
                      "got unexpected status %04X from get response\n",
 
2820
                      slot, sw);
 
2821
        }
 
2822
      while ((sw & 0xff00) == SW_MORE_DATA);
 
2823
      
 
2824
      if (retbuf)
 
2825
        {
 
2826
          *retbuflen = p - *retbuf;
 
2827
          tmp = xtryrealloc (*retbuf, *retbuflen);
 
2828
          if (tmp)
 
2829
            *retbuf = tmp;
 
2830
        }
 
2831
    }
 
2832
 
 
2833
  unlock_slot (slot);
 
2834
 
 
2835
  if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
 
2836
    log_printhex ("      dump: ", *retbuf, *retbuflen);
 
2837
 
 
2838
  return sw;
 
2839
#undef RESULTLEN
 
2840
}
 
2841
 
 
2842
/* Send an APDU to the card in SLOT.  The APDU is created from all
 
2843
   given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
 
2844
   LC won't sent this field and the data field; in this case DATA must
 
2845
   also be passed as NULL. The return value is the status word or -1
 
2846
   for an invalid SLOT or other non card related error.  If RETBUF is
 
2847
   not NULL, it will receive an allocated buffer with the returned
 
2848
   data.  The length of that data will be put into *RETBUFLEN.  The
 
2849
   caller is reponsible for releasing the buffer even in case of
 
2850
   errors.  */
 
2851
int 
 
2852
apdu_send (int slot, int class, int ins, int p0, int p1,
 
2853
           int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
 
2854
{
 
2855
  return apdu_send_le (slot, class, ins, p0, p1, lc, data, 256, 
 
2856
                       retbuf, retbuflen);
 
2857
}
 
2858
 
 
2859
/* Send an APDU to the card in SLOT.  The APDU is created from all
 
2860
   given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
 
2861
   LC won't sent this field and the data field; in this case DATA must
 
2862
   also be passed as NULL. The return value is the status word or -1
 
2863
   for an invalid SLOT or other non card related error.  No data will be
 
2864
   returned. */
 
2865
int 
 
2866
apdu_send_simple (int slot, int class, int ins, int p0, int p1,
 
2867
                  int lc, const char *data)
 
2868
{
 
2869
  return apdu_send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL);
 
2870
}
 
2871
 
 
2872
 
 
2873
/* This is a more generic version of the apdu sending routine.  It
 
2874
   takes an already formatted APDU in APDUDATA or length APDUDATALEN
 
2875
   and returns the with the APDU including the status word.  With
 
2876
   HANDLE_MORE set to true this function will handle the MORE DATA
 
2877
   status and return all APDUs concatenated with one status word at
 
2878
   the end.  The function does not return a regular status word but 0
 
2879
   on success.  If the slot is locked, the fucntion returns
 
2880
   immediately.*/
 
2881
int 
 
2882
apdu_send_direct (int slot, const unsigned char *apdudata, size_t apdudatalen,
 
2883
                  int handle_more,
 
2884
                  unsigned char **retbuf, size_t *retbuflen)
 
2885
{
 
2886
#define RESULTLEN 256
 
2887
  unsigned char apdu[5+256+1];
 
2888
  size_t apdulen;
 
2889
  unsigned char result[RESULTLEN+10]; /* 10 extra in case of bugs in
 
2890
                                         the driver. */
 
2891
  size_t resultlen;
 
2892
  int sw;
 
2893
  long rc; /* we need a long here due to PC/SC. */
 
2894
  int class;
 
2895
 
 
2896
  if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
 
2897
    return SW_HOST_NO_DRIVER;
 
2898
 
 
2899
  if ((sw = trylock_slot (slot)))
 
2900
    return sw;
 
2901
 
 
2902
  /* We simply trucntate a too long APDU.  */
 
2903
  if (apdudatalen > sizeof apdu)
 
2904
    apdudatalen = sizeof apdu;
 
2905
  apdulen = apdudatalen;
 
2906
  memcpy (apdu, apdudata, apdudatalen);
 
2907
  class = apdulen? *apdu : 0;
 
2908
 
 
2909
 
 
2910
  rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
 
2911
  if (rc || resultlen < 2)
 
2912
    {
 
2913
      log_error ("apdu_send_direct(%d) failed: %s\n",
 
2914
                 slot, apdu_strerror (rc));
 
2915
      unlock_slot (slot);
 
2916
      return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2917
    }
 
2918
  sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2919
  /* Store away the returned data but strip the statusword. */
 
2920
  resultlen -= 2;
 
2921
  if (DBG_CARD_IO)
 
2922
    {
 
2923
      log_debug (" response: sw=%04X  datalen=%d\n", sw, resultlen);
 
2924
      if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
 
2925
        log_printhex ("     dump: ", result, resultlen);
 
2926
    }
 
2927
 
 
2928
  if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
 
2929
    {
 
2930
      unsigned char *p = NULL, *tmp;
 
2931
      size_t bufsize = 4096;
 
2932
 
 
2933
      /* It is likely that we need to return much more data, so we
 
2934
         start off with a large buffer. */
 
2935
      if (retbuf)
 
2936
        {
 
2937
          *retbuf = p = xtrymalloc (bufsize + 2);
 
2938
          if (!*retbuf)
 
2939
            {
 
2940
              unlock_slot (slot);
 
2941
              return SW_HOST_OUT_OF_CORE;
 
2942
            }
 
2943
          assert (resultlen < bufsize);
 
2944
          memcpy (p, result, resultlen);
 
2945
          p += resultlen;
 
2946
        }
 
2947
 
 
2948
      do
 
2949
        {
 
2950
          int len = (sw & 0x00ff);
 
2951
          
 
2952
          if (DBG_CARD_IO)
 
2953
            log_debug ("apdu_send_direct(%d): %d more bytes available\n",
 
2954
                       slot, len);
 
2955
          apdulen = 0;
 
2956
          apdu[apdulen++] = class;
 
2957
          apdu[apdulen++] = 0xC0;
 
2958
          apdu[apdulen++] = 0;
 
2959
          apdu[apdulen++] = 0;
 
2960
          apdu[apdulen++] = len; 
 
2961
          memset (apdu+apdulen, 0, sizeof (apdu) - apdulen);
 
2962
          resultlen = RESULTLEN;
 
2963
          rc = send_apdu (slot, apdu, apdulen, result, &resultlen);
 
2964
          if (rc || resultlen < 2)
 
2965
            {
 
2966
              log_error ("apdu_send_direct(%d) for get response failed: %s\n",
 
2967
                         slot, apdu_strerror (rc));
 
2968
              unlock_slot (slot);
 
2969
              return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
 
2970
            }
 
2971
          sw = (result[resultlen-2] << 8) | result[resultlen-1];
 
2972
          resultlen -= 2;
 
2973
          if (DBG_CARD_IO)
 
2974
            {
 
2975
              log_debug ("     more: sw=%04X  datalen=%d\n", sw, resultlen);
 
2976
              if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
 
2977
                log_printhex ("     dump: ", result, resultlen);
 
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