Imported Upstream version 2.1.12
[platform/upstream/gpg2.git] / scd / command.c
index fc1f5a2..72ff132 100644 (file)
@@ -1,6 +1,6 @@
 /* command.c - SCdaemon command handler
  * Copyright (C) 2001, 2002, 2003, 2004, 2005,
- *               2007, 2008, 2009  Free Software Foundation, Inc.
+ *               2007, 2008, 2009, 2011  Free Software Foundation, Inc.
  *
  * This file is part of GnuPG.
  *
@@ -26,8 +26,8 @@
 #include <ctype.h>
 #include <unistd.h>
 #include <signal.h>
-#ifdef USE_GNU_PTH
-# include <pth.h>
+#ifdef USE_NPTH
+# include <npth.h>
 #endif
 
 #include "scdaemon.h"
 #include "app-common.h"
 #include "iso7816.h"
 #include "apdu.h" /* Required for apdu_*_reader (). */
+#include "atr.h"
 #include "exechelp.h"
 #ifdef HAVE_LIBUSB
 #include "ccid-driver.h"
 #endif
+#include "asshelp.h"
+#include "server-help.h"
 
 /* Maximum length allowed as a PIN; used for INQUIRE NEEDPIN */
 #define MAXLEN_PIN 100
@@ -57,7 +60,7 @@
 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
 
 
-/* Macro to flag a removed card.  ENODEV is also tested to catch teh
+/* Macro to flag a removed card.  ENODEV is also tested to catch the
    case of a removed reader.  */
 #define TEST_CARD_REMOVAL(c,r)                              \
        do {                                                 \
               || gpg_err_code (_r) == GPG_ERR_CARD_REMOVED  \
               || gpg_err_code (_r) == GPG_ERR_CARD_RESET    \
               || gpg_err_code (_r) == GPG_ERR_ENODEV )      \
-            update_card_removed ((c)->reader_slot, 1);      \
+            update_card_removed ((c)->server_local->vreader_idx, 1);      \
        } while (0)
 
-#define IS_LOCKED(c)                                                     \
-     (locked_session && locked_session != (c)->server_local              \
-      && (c)->reader_slot != -1 && locked_session->ctrl_backlink         \
-      && (c)->reader_slot == locked_session->ctrl_backlink->reader_slot)
+#define IS_LOCKED(c)                                                    \
+  (locked_session                                                       \
+   && locked_session != (c)->server_local                               \
+   && (c)->server_local->vreader_idx != -1                              \
+   && locked_session->ctrl_backlink                                     \
+   && ((c)->server_local->vreader_idx                                   \
+       == locked_session->ctrl_backlink->server_local->vreader_idx))
 
 
-/* This structure is used to keep track of open readers (slots). */
-struct slot_status_s
+/* This structure is used to keep track of user readers.  To
+   eventually accommodate this structure for RFID cards, where more
+   than one card is used per reader, we name it virtual reader.  */
+struct vreader_s
 {
   int valid;  /* True if the other objects are valid. */
-  int slot;   /* Slot number of the reader or -1 if not open. */
+  int slot;   /* APDU slot number of the reader or -1 if not open. */
 
   int reset_failed; /* A reset failed. */
 
   int any;    /* Flag indicating whether any status check has been
                  done.  This is set once to indicate that the status
                  tracking for the slot has been initialized.  */
-  unsigned int status;  /* Last status of the slot. */
-  unsigned int changed; /* Last change counter of the slot. */
+  unsigned int status;  /* Last status of the reader. */
+  unsigned int changed; /* Last change counter of the reader. */
 };
 
 
@@ -114,6 +122,9 @@ struct server_local_s
   int event_signal;             /* Or 0 if not used. */
 #endif
 
+  /* Index into the vreader table (command.c) or -1 if not open. */
+  int vreader_idx;
+
   /* True if the card has been removed and a reset is required to
      continue operation. */
   int card_removed;
@@ -132,10 +143,8 @@ struct server_local_s
 };
 
 
-/* The table with information on all used slots.  FIXME: This is a
-   different slot number than the one used by the APDU layer, and
-   should be renamed.  */
-static struct slot_status_s slot_table[10];
+/* The table with information on all used virtual readers.  */
+static struct vreader_s vreader_table[10];
 
 
 /* To keep track of all running sessions, we link all active server
@@ -148,7 +157,7 @@ static struct server_local_s *locked_session;
 
 /* While doing a reset we need to make sure that the ticker does not
    call scd_update_reader_status_file while we are using it. */
-static pth_mutex_t status_file_update_lock;
+static npth_mutex_t status_file_update_lock;
 
 \f
 /*-- Local prototypes --*/
@@ -165,85 +174,52 @@ void
 initialize_module_command (void)
 {
   static int initialized;
+  int err;
 
   if (!initialized)
     {
-      if (pth_mutex_init (&status_file_update_lock))
+      err = npth_mutex_init (&status_file_update_lock, NULL);
+      if (!err)
         initialized = 1;
     }
 }
 
 
-/* Update the CARD_REMOVED element of all sessions using the reader
-   given by SLOT to VALUE.  */
+/* Helper to return the slot number for a given virtual reader index
+   VRDR.  In case on an error -1 is returned.  */
+static int
+vreader_slot (int vrdr)
+{
+  if (vrdr == -1 || !(vrdr >= 0 && vrdr < DIM(vreader_table)))
+    return -1;
+  if (!vreader_table [vrdr].valid)
+    return -1;
+  return vreader_table[vrdr].slot;
+}
+
+
+/* Update the CARD_REMOVED element of all sessions using the virtual
+   reader given by VRDR to VALUE.  */
 static void
-update_card_removed (int slot, int value)
+update_card_removed (int vrdr, int value)
 {
   struct server_local_s *sl;
 
-  if (slot == -1)
+  if (vrdr == -1)
     return;
 
   for (sl=session_list; sl; sl = sl->next_session)
     if (sl->ctrl_backlink
-        && sl->ctrl_backlink->reader_slot == slot)
+        && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
       {
         sl->card_removed = value;
       }
   /* Let the card application layer know about the removal.  */
   if (value)
-    application_notify_card_reset (slot);
-}
-
-
-
-/* Check whether the option NAME appears in LINE.  Returns 1 or 0. */
-static int
-has_option (const char *line, const char *name)
-{
-  const char *s;
-  int n = strlen (name);
-
-  s = strstr (line, name);
-  return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
-}
-
-/* Same as has_option but does only test for the name of the option
-   and ignores an argument, i.e. with NAME being "--hash" it would
-   return a pointer for "--hash" as well as for "--hash=foo".  If
-   there is no such option NULL is returned.  The pointer returned
-   points right behind the option name, this may be an equal sign, Nul
-   or a space.  */
-static const char *
-has_option_name (const char *line, const char *name)
-{
-  const char *s;
-  int n = strlen (name);
-
-  s = strstr (line, name);
-  return (s && (s == line || spacep (s-1))
-          && (!s[n] || spacep (s+n) || s[n] == '=')) ? (s+n) : NULL;
+    application_notify_card_reset (vreader_slot (vrdr));
 }
 
 
-/* Skip over options.  It is assumed that leading spaces have been
-   removed (this is the case for lines passed to a handler from
-   assuan).  Blanks after the options are also removed. */
-static char *
-skip_options (char *line)
-{
-  while ( *line == '-' && line[1] == '-' )
-    {
-      while (*line && !spacep (line))
-        line++;
-      while (spacep (line))
-        line++;
-    }
-  return line;
-}
-
-
-
 /* Convert the STRING into a newly allocated buffer while translating
    the hex numbers.  Stops at the first invalid character.  Blanks and
    colons are allowed to separate the hex digits.  Returns NULL on
@@ -282,9 +258,11 @@ hex_to_buffer (const char *string, size_t *r_length)
 static void
 do_reset (ctrl_t ctrl, int send_reset)
 {
-  int slot = ctrl->reader_slot;
+  int vrdr = ctrl->server_local->vreader_idx;
+  int slot;
+  int err;
 
-  if (!(slot == -1 || (slot >= 0 && slot < DIM(slot_table))))
+  if (!(vrdr == -1 || (vrdr >= 0 && vrdr < DIM(vreader_table))))
     BUG ();
 
   /* If there is an active application, release it.  Tell all other
@@ -300,7 +278,7 @@ do_reset (ctrl_t ctrl, int send_reset)
 
           for (sl=session_list; sl; sl = sl->next_session)
             if (sl->ctrl_backlink
-                && sl->ctrl_backlink->reader_slot == slot)
+                && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
               {
                 sl->app_ctx_marked_for_release = 1;
               }
@@ -309,21 +287,22 @@ do_reset (ctrl_t ctrl, int send_reset)
 
   /* If we want a real reset for the card, send the reset APDU and
      tell the application layer about it.  */
+  slot = vreader_slot (vrdr);
   if (slot != -1 && send_reset && !IS_LOCKED (ctrl) )
     {
       application_notify_card_reset (slot);
       switch (apdu_reset (slot))
-       {
-       case 0:
-         break;
-       case SW_HOST_NO_CARD:
-       case SW_HOST_CARD_INACTIVE:
-         break;
-       default:
+        {
+        case 0:
+          break;
+        case SW_HOST_NO_CARD:
+        case SW_HOST_CARD_INACTIVE:
+          break;
+        default:
          apdu_close_reader (slot);
-         slot_table[slot].slot = -1;
-         break;
-       }
+          vreader_table[vrdr].slot = slot = -1;
+          break;
+        }
     }
 
   /* If we hold a lock, unlock now. */
@@ -336,21 +315,24 @@ do_reset (ctrl_t ctrl, int send_reset)
   /* Reset the card removed flag for the current reader.  We need to
      take the lock here so that the ticker thread won't concurrently
      try to update the file.  Calling update_reader_status_file is
-     required to get hold of the new status of the card in the slot
+     required to get hold of the new status of the card in the vreader
      table.  */
-  if (!pth_mutex_acquire (&status_file_update_lock, 0, NULL))
+  err = npth_mutex_lock (&status_file_update_lock);
+  if (err)
     {
-      log_error ("failed to acquire status_fle_update lock\n");
-      ctrl->reader_slot = -1;
+      log_error ("failed to acquire status_file_update lock\n");
+      ctrl->server_local->vreader_idx = -1;
       return;
     }
   update_reader_status_file (0);  /* Update slot status table.  */
-  update_card_removed (slot, 0);  /* Clear card_removed flag.  */
-  if (!pth_mutex_release (&status_file_update_lock))
-    log_error ("failed to release status_file_update lock\n");
+  update_card_removed (vrdr, 0);  /* Clear card_removed flag.  */
+  err = npth_mutex_unlock (&status_file_update_lock);
+  if (err)
+    log_error ("failed to release status_file_update lock: %s\n",
+              strerror (err));
 
   /* Do this last, so that the update_card_removed above does its job.  */
-  ctrl->reader_slot = -1;
+  ctrl->server_local->vreader_idx = -1;
 }
 
 \f
@@ -390,40 +372,41 @@ option_handler (assuan_context_t ctx, const char *key, const char *value)
 }
 
 
-/* Return the slot of the current reader or open the reader if no
-   other sessions are using a reader.  Note, that we currently support
+/* Return the index of the current reader or open the reader if no
+   other sessions are using that reader.  If it is not possible to
+   open the reader -1 is returned.  Note, that we currently support
    only one reader but most of the code (except for this function)
    should be able to cope with several readers.  */
 static int
-get_reader_slot (void)
+get_current_reader (void)
 {
-  struct slot_status_s *ss;
+  struct vreader_s *vr;
 
-  ss = &slot_table[0]; /* One reader for now. */
+  /* We only support one reader for now.  */
+  vr = &vreader_table[0];
 
-  /* Initialize the item if needed. */
-  if (!ss->valid)
+  /* Initialize the vreader item if not yet done. */
+  if (!vr->valid)
     {
-      ss->slot = -1;
-      ss->valid = 1;
+      vr->slot = -1;
+      vr->valid = 1;
     }
 
   /* Try to open the reader. */
-  if (ss->slot == -1)
+  if (vr->slot == -1)
     {
-      ss->slot = apdu_open_reader (opt.reader_port);
+      vr->slot = apdu_open_reader (opt.reader_port);
 
       /* If we still don't have a slot, we have no readers.
         Invalidate for now until a reader is attached. */
-      if(ss->slot == -1)
+      if (vr->slot == -1)
        {
-         ss->valid = 0;
-         return -1;
+         vr->valid = 0;
        }
     }
 
-  /* Return the slot_table index.  */
-  return 0;
+  /* Return the vreader index or -1.  */
+  return vr->valid ? 0 : -1;
 }
 
 
@@ -432,7 +415,7 @@ static gpg_error_t
 open_card (ctrl_t ctrl, const char *apptype)
 {
   gpg_error_t err;
-  int slot;
+  int vrdr;
 
   /* If we ever got a card not present error code, return that.  Only
      the SERIALNO command and a reset are able to clear from that
@@ -457,21 +440,25 @@ open_card (ctrl_t ctrl, const char *apptype)
      need to check that the client didn't requested a specific
      application different from the one in use before we continue. */
   if (ctrl->app_ctx)
-    return check_application_conflict (ctrl, apptype);
+    {
+      return check_application_conflict
+        (ctrl, vreader_slot (ctrl->server_local->vreader_idx), apptype);
+    }
 
-  /* Setup the slot and select the application.  */
-  if (ctrl->reader_slot != -1)
-    slot = ctrl->reader_slot;
+  /* Setup the vreader and select the application.  */
+  if (ctrl->server_local->vreader_idx != -1)
+    vrdr = ctrl->server_local->vreader_idx;
   else
-    slot = get_reader_slot ();
-  ctrl->reader_slot = slot;
-  if (slot == -1)
+    vrdr = get_current_reader ();
+  ctrl->server_local->vreader_idx = vrdr;
+  if (vrdr == -1)
     err = gpg_error (GPG_ERR_CARD);
   else
     {
       /* Fixme: We should move the apdu_connect call to
          select_application.  */
       int sw;
+      int slot = vreader_slot (vrdr);
 
       ctrl->server_local->disconnect_allowed = 0;
       sw = apdu_connect (slot);
@@ -482,8 +469,8 @@ open_card (ctrl_t ctrl, const char *apptype)
           else if (sw == SW_HOST_CARD_INACTIVE)
             err = gpg_error (GPG_ERR_CARD_RESET);
           else
-            err = gpg_error (GPG_ERR_CARD);
-       }
+            err = gpg_error (GPG_ERR_ENODEV);
+        }
       else
         err = select_application (ctrl, slot, apptype, &ctrl->app_ctx);
     }
@@ -496,7 +483,7 @@ open_card (ctrl_t ctrl, const char *apptype)
 static const char hlp_serialno[] =
   "SERIALNO [<apptype>]\n"
   "\n"
-  "Return the serial number of the card using a status reponse.  This\n"
+  "Return the serial number of the card using a status response.  This\n"
   "function should be used to check for the presence of a card.\n"
   "\n"
   "If APPTYPE is given, an application of that type is selected and an\n"
@@ -517,7 +504,6 @@ cmd_serialno (assuan_context_t ctx, char *line)
 {
   ctrl_t ctrl = assuan_get_pointer (ctx);
   int rc = 0;
-  char *serial_and_stamp;
   char *serial;
   time_t stamp;
   int retries = 0;
@@ -543,15 +529,10 @@ cmd_serialno (assuan_context_t ctx, char *line)
   if (rc)
     return rc;
 
-  rc = estream_asprintf (&serial_and_stamp, "%s %lu",
-                         serial, (unsigned long)stamp);
+  rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
+                            serial, (unsigned long)stamp);
   xfree (serial);
-  if (rc < 0)
-    return out_of_core ();
-  rc = 0;
-  assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
-  xfree (serial_and_stamp);
-  return 0;
+  return rc;
 }
 
 
@@ -640,32 +621,41 @@ cmd_learn (assuan_context_t ctx, char *line)
      knows about this card */
   if (!only_keypairinfo)
     {
-      char *serial_and_stamp;
+      int slot;
+      const char *reader;
       char *serial;
       time_t stamp;
 
+      slot = vreader_slot (ctrl->server_local->vreader_idx);
+      reader = apdu_get_reader_name (slot);
+      if (!reader)
+        return out_of_core ();
+      send_status_direct (ctrl, "READER", reader);
+      /* No need to free the string of READER.  */
+
       rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
       if (rc)
         return rc;
-      rc = estream_asprintf (&serial_and_stamp, "%s %lu",
-                             serial, (unsigned long)stamp);
-      xfree (serial);
+
+      rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
+                                serial, (unsigned long)stamp);
       if (rc < 0)
-        return out_of_core ();
-      rc = 0;
-      assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
+        {
+          xfree (serial);
+          return out_of_core ();
+        }
 
       if (!has_option (line, "--force"))
         {
           char *command;
 
-          rc = estream_asprintf (&command, "KNOWNCARDP %s", serial_and_stamp);
+          rc = gpgrt_asprintf (&command, "KNOWNCARDP %s %lu",
+                               serial, (unsigned long)stamp);
           if (rc < 0)
             {
-              xfree (serial_and_stamp);
+              xfree (serial);
               return out_of_core ();
             }
-          rc = 0;
           rc = assuan_inquire (ctx, command, NULL, NULL, 0);
           xfree (command);
           if (rc)
@@ -673,12 +663,12 @@ cmd_learn (assuan_context_t ctx, char *line)
               if (gpg_err_code (rc) != GPG_ERR_ASS_CANCELED)
                 log_error ("inquire KNOWNCARDP failed: %s\n",
                            gpg_strerror (rc));
-              xfree (serial_and_stamp);
+              xfree (serial);
               return rc;
             }
           /* Not canceled, so we have to proceeed.  */
         }
-      xfree (serial_and_stamp);
+      xfree (serial);
     }
 
   /* Let the application print out its collection of useful status
@@ -777,10 +767,8 @@ cmd_readkey (assuan_context_t ctx, char *line)
 
   rc = ksba_cert_new (&kc);
   if (rc)
-    {
-      xfree (cert);
-      goto leave;
-    }
+    goto leave;
+
   rc = ksba_cert_init_from_mem (kc, cert, ncert);
   if (rc)
     {
@@ -849,7 +837,7 @@ cmd_setdata (assuan_context_t ctx, char *line)
       buf = xtrymalloc (ctrl->in_data.valuelen + n);
     }
   else
-  buf = xtrymalloc (n);
+    buf = xtrymalloc (n);
   if (!buf)
     return out_of_core ();
 
@@ -863,8 +851,9 @@ cmd_setdata (assuan_context_t ctx, char *line)
   for (p=line, i=0; i < n; p += 2, i++)
     buf[off+i] = xtoi_2 (p);
 
+  xfree (ctrl->in_data.value);
   ctrl->in_data.value = buf;
-  ctrl->in_data.valuelen = off + n;
+  ctrl->in_data.valuelen = off+n;
   return 0;
 }
 
@@ -887,7 +876,7 @@ pin_cb (void *opaque, const char *info, char **retstr)
       if (info)
         {
           log_debug ("prompting for pinpad entry '%s'\n", info);
-          rc = estream_asprintf (&command, "POPUPPINPADPROMPT %s", info);
+          rc = gpgrt_asprintf (&command, "POPUPPINPADPROMPT %s", info);
           if (rc < 0)
             return gpg_error (gpg_err_code_from_errno (errno));
           rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
@@ -907,7 +896,7 @@ pin_cb (void *opaque, const char *info, char **retstr)
   *retstr = NULL;
   log_debug ("asking for PIN '%s'\n", info);
 
-  rc = estream_asprintf (&command, "NEEDPIN %s", info);
+  rc = gpgrt_asprintf (&command, "NEEDPIN %s", info);
   if (rc < 0)
     return gpg_error (gpg_err_code_from_errno (errno));
 
@@ -1061,6 +1050,7 @@ cmd_pkdecrypt (assuan_context_t ctx, char *line)
   unsigned char *outdata;
   size_t outdatalen;
   char *keyidstr;
+  unsigned int infoflags;
 
   if ( IS_LOCKED (ctrl) )
     return gpg_error (GPG_ERR_LOCKED);
@@ -1075,7 +1065,7 @@ cmd_pkdecrypt (assuan_context_t ctx, char *line)
                      keyidstr,
                      pin_cb, ctx,
                      ctrl->in_data.value, ctrl->in_data.valuelen,
-                     &outdata, &outdatalen);
+                     &outdata, &outdatalen, &infoflags);
 
   xfree (keyidstr);
   if (rc)
@@ -1084,6 +1074,13 @@ cmd_pkdecrypt (assuan_context_t ctx, char *line)
     }
   else
     {
+      /* If the card driver told us that there is no padding, send a
+         status line.  If there is a padding it is assumed that the
+         caller knows what padding is used.  It would have been better
+         to always send that information but for backward
+         compatibility we can't do that.  */
+      if ((infoflags & APP_DECIPHER_INFO_NOPAD))
+        send_status_direct (ctrl, "PADDING", "0");
       rc = assuan_send_data (ctx, outdata, outdatalen);
       xfree (outdata);
       if (rc)
@@ -1104,7 +1101,7 @@ static const char hlp_getattr[] =
   "returned through status message, see the LEARN command for details.\n"
   "\n"
   "However, the current implementation assumes that Name is not escaped;\n"
-  "this works as long as noone uses arbitrary escaping. \n"
+  "this works as long as no one uses arbitrary escaping. \n"
   "\n"
   "Note, that this function may even be used on a locked card.";
 static gpg_error_t
@@ -1142,7 +1139,7 @@ static const char hlp_setattr[] =
   "application.  NAME and VALUE must be percent and '+' escaped.\n"
   "\n"
   "However, the current implementation assumes that NAME is not\n"
-  "escaped; this works as long as noone uses arbitrary escaping.\n"
+  "escaped; this works as long as no one uses arbitrary escaping.\n"
   "\n"
   "A PIN will be requested for most NAMEs.  See the corresponding\n"
   "setattr function of the actually used application (app-*.c) for\n"
@@ -1444,7 +1441,7 @@ static const char hlp_passwd[] =
   "PASSWD [--reset] [--nullpin] <chvno>\n"
   "\n"
   "Change the PIN or, if --reset is given, reset the retry counter of\n"
-  "the card holder verfication vector CHVNO.  The option --nullpin is\n"
+  "the card holder verification vector CHVNO.  The option --nullpin is\n"
   "used for TCOS cards to set the initial PIN.  The format of CHVNO\n"
   "depends on the card application.";
 static gpg_error_t
@@ -1581,18 +1578,18 @@ cmd_lock (assuan_context_t ctx, char *line)
   else
     locked_session = ctrl->server_local;
 
-#ifdef USE_GNU_PTH
+#ifdef USE_NPTH
   if (rc && has_option (line, "--wait"))
     {
       rc = 0;
-      pth_sleep (1); /* Better implement an event mechanism. However,
-                        for card operations this should be
-                        sufficient. */
+      npth_sleep (1); /* Better implement an event mechanism. However,
+                        for card operations this should be
+                        sufficient. */
       /* FIXME: Need to check that the connection is still alive.
          This can be done by issuing status messages. */
       goto retry;
     }
-#endif /*USE_GNU_PTH*/
+#endif /*USE_NPTH*/
 
   if (rc)
     log_error ("cmd_lock failed: %s\n", gpg_strerror (rc));
@@ -1639,8 +1636,8 @@ static const char hlp_getinfo[] =
   "\n"
   "socket_name - Return the name of the socket.\n"
   "\n"
-  "status - Return the status of the current slot (in the future, may\n"
-  "also return the status of all slots).  The status is a list of\n"
+  "status - Return the status of the current reader (in the future, may\n"
+  "also return the status of all readers).  The status is a list of\n"
   "one-character flags.  The following flags are currently defined:\n"
   "  'u'  Usable card present.  This is the normal state during operation.\n"
   "  'r'  Card removed.  A reset is necessary.\n"
@@ -1684,19 +1681,18 @@ cmd_getinfo (assuan_context_t ctx, char *line)
   else if (!strcmp (line, "status"))
     {
       ctrl_t ctrl = assuan_get_pointer (ctx);
-      int slot = ctrl->reader_slot;
+      int vrdr = ctrl->server_local->vreader_idx;
       char flag = 'r';
 
-      if (!ctrl->server_local->card_removed && slot != -1)
+      if (!ctrl->server_local->card_removed && vrdr != -1)
        {
-         struct slot_status_s *ss;
+         struct vreader_s *vr;
 
-         if (!(slot >= 0 && slot < DIM(slot_table)))
+         if (!(vrdr >= 0 && vrdr < DIM(vreader_table)))
            BUG ();
 
-         ss = &slot_table[slot];
-
-         if (ss->valid && ss->any && (ss->status & 1))
+         vr = &vreader_table[vrdr];
+         if (vr->valid && vr->any && (vr->status & 1))
            flag = 'u';
        }
       rc = assuan_send_data (ctx, &flag, 1);
@@ -1782,7 +1778,7 @@ cmd_disconnect (assuan_context_t ctx, char *line)
 
 
 static const char hlp_apdu[] =
-  "APDU [--atr] [--more] [--exlen[=N]] [hexstring]\n"
+  "APDU [--[dump-]atr] [--more] [--exlen[=N]] [hexstring]\n"
   "\n"
   "Send an APDU to the current reader.  This command bypasses the high\n"
   "level functions and sends the data directly to the card.  HEXSTRING\n"
@@ -1795,7 +1791,7 @@ static const char hlp_apdu[] =
   "  S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1\n"
   "\n"
   "Using the option --more handles the card status word MORE_DATA\n"
-  "(61xx) and concatenates all reponses to one block.\n"
+  "(61xx) and concatenates all responses to one block.\n"
   "\n"
   "Using the option \"--exlen\" the returned APDU may use extended\n"
   "length up to N bytes.  If N is not given a default value is used\n"
@@ -1811,8 +1807,12 @@ cmd_apdu (assuan_context_t ctx, char *line)
   int handle_more;
   const char *s;
   size_t exlen;
+  int slot;
 
-  with_atr = has_option (line, "--atr");
+  if (has_option (line, "--dump-atr"))
+    with_atr = 2;
+  else
+    with_atr = has_option (line, "--atr");
   handle_more = has_option (line, "--more");
 
   if ((s=has_option_name (line, "--exlen")))
@@ -1833,21 +1833,46 @@ cmd_apdu (assuan_context_t ctx, char *line)
   if ((rc = open_card (ctrl, NULL)))
     return rc;
 
+  slot = vreader_slot (ctrl->server_local->vreader_idx);
+
   if (with_atr)
     {
       unsigned char *atr;
       size_t atrlen;
       char hexbuf[400];
 
-      atr = apdu_get_atr (ctrl->reader_slot, &atrlen);
+      atr = apdu_get_atr (slot, &atrlen);
       if (!atr || atrlen > sizeof hexbuf - 2 )
         {
           rc = gpg_error (GPG_ERR_INV_CARD);
           goto leave;
         }
-      bin2hex (atr, atrlen, hexbuf);
+      if (with_atr == 2)
+        {
+          char *string, *p, *pend;
+
+          string = atr_dump (atr, atrlen);
+          if (string)
+            {
+              for (rc=0, p=string; !rc && (pend = strchr (p, '\n')); p = pend+1)
+                {
+                  rc = assuan_send_data (ctx, p, pend - p + 1);
+                  if (!rc)
+                    rc = assuan_send_data (ctx, NULL, 0);
+                }
+              if (!rc && *p)
+                rc = assuan_send_data (ctx, p, strlen (p));
+              es_free (string);
+              if (rc)
+                goto leave;
+            }
+        }
+      else
+        {
+          bin2hex (atr, atrlen, hexbuf);
+          send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
+        }
       xfree (atr);
-      send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
     }
 
   apdu = hex_to_buffer (line, &apdulen);
@@ -1861,7 +1886,7 @@ cmd_apdu (assuan_context_t ctx, char *line)
       unsigned char *result = NULL;
       size_t resultlen;
 
-      rc = apdu_send_direct (ctrl->reader_slot, exlen,
+      rc = apdu_send_direct (slot, exlen,
                              apdu, apdulen, handle_more,
                              &result, &resultlen);
       if (rc)
@@ -1892,7 +1917,8 @@ cmd_killscd (assuan_context_t ctx, char *line)
   (void)line;
 
   ctrl->server_local->stopme = 1;
-  return gpg_error (GPG_ERR_EOF);
+  assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
+  return 0;
 }
 
 
@@ -2003,15 +2029,13 @@ scd_command_handler (ctrl_t ctrl, int fd)
   session_list = ctrl->server_local;
   ctrl->server_local->ctrl_backlink = ctrl;
   ctrl->server_local->assuan_ctx = ctx;
-
-  if (DBG_ASSUAN)
-    assuan_set_log_stream (ctx, log_get_stream ());
+  ctrl->server_local->vreader_idx = -1;
 
   /* We open the reader right at startup so that the ticker is able to
      update the status file. */
-  if (ctrl->reader_slot == -1)
+  if (ctrl->server_local->vreader_idx == -1)
     {
-      ctrl->reader_slot = get_reader_slot ();
+      ctrl->server_local->vreader_idx = get_current_reader ();
     }
 
   /* Command processing loop. */
@@ -2217,24 +2241,24 @@ update_reader_status_file (int set_card_removed_flag)
      make sense to wait here for a operation to complete.  If we are
      busy working with a card, delays in the status file update should
      be acceptable. */
-  for (idx=0; idx < DIM(slot_table); idx++)
+  for (idx=0; idx < DIM(vreader_table); idx++)
     {
-      struct slot_status_s *ss = slot_table + idx;
+      struct vreader_s *vr = vreader_table + idx;
       struct server_local_s *sl;
       int sw_apdu;
 
-      if (!ss->valid || ss->slot == -1)
+      if (!vr->valid || vr->slot == -1)
         continue; /* Not valid or reader not yet open. */
 
-      sw_apdu = apdu_get_status (ss->slot, 0, &status, &changed);
+      sw_apdu = apdu_get_status (vr->slot, 0, &status, &changed);
       if (sw_apdu == SW_HOST_NO_READER)
         {
           /* Most likely the _reader_ has been unplugged.  */
-         application_notify_card_reset (ss->slot);
-         apdu_close_reader (ss->slot);
-         ss->valid = 0;
+          application_notify_card_reset (vr->slot);
+         apdu_close_reader (vr->slot);
+          vr->slot = -1;
           status = 0;
-          changed = ss->changed;
+          changed = vr->changed;
         }
       else if (sw_apdu)
         {
@@ -2242,21 +2266,21 @@ update_reader_status_file (int set_card_removed_flag)
           continue;
         }
 
-      if (!ss->any || ss->status != status || ss->changed != changed )
+      if (!vr->any || vr->status != status || vr->changed != changed )
         {
           char *fname;
           char templ[50];
           FILE *fp;
 
-          log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
-                    ss->slot, ss->status, status, ss->changed, changed);
-          ss->status = status;
-          ss->changed = changed;
+          log_info ("updating reader %d (%d) status: 0x%04X->0x%04X (%u->%u)\n",
+                    idx, vr->slot, vr->status, status, vr->changed, changed);
+          vr->status = status;
+          vr->changed = changed;
 
-         /* FIXME: Should this be IDX instead of ss->slot?  This
+         /* FIXME: Should this be IDX instead of vr->slot?  This
             depends on how client sessions will associate the reader
             status with their session.  */
-          snprintf (templ, sizeof templ, "reader_%d.status", ss->slot);
+          snprintf (templ, sizeof templ, "reader_%d.status", vr->slot);
           fname = make_filename (opt.homedir, templ, NULL );
           fp = fopen (fname, "w");
           if (fp)
@@ -2277,15 +2301,15 @@ update_reader_status_file (int set_card_removed_flag)
             gpg_error_t err;
 
             homestr = make_filename (opt.homedir, NULL);
-            if (estream_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
+            if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
               log_error ("out of core while building environment\n");
             else
               {
                 envs[0] = envstr;
                 envs[1] = NULL;
 
-                sprintf (numbuf1, "%d", ss->slot);
-                sprintf (numbuf2, "0x%04X", ss->status);
+                sprintf (numbuf1, "%d", vr->slot);
+                sprintf (numbuf2, "0x%04X", vr->status);
                 sprintf (numbuf3, "0x%04X", status);
                 args[0] = "--reader-port";
                 args[1] = numbuf1;
@@ -2302,7 +2326,7 @@ update_reader_status_file (int set_card_removed_flag)
                 fname = make_filename (opt.homedir, "scd-event", NULL);
                 err = gnupg_spawn_process_detached (fname, args, envs);
                 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
-                  log_error ("failed to run event handler `%s': %s\n",
+                  log_error ("failed to run event handler '%s': %s\n",
                              fname, gpg_strerror (err));
                 xfree (fname);
                 xfree (envstr);
@@ -2311,10 +2335,10 @@ update_reader_status_file (int set_card_removed_flag)
           }
 
           /* Set the card removed flag for all current sessions.  */
-          if (ss->any && ss->status == 0 && set_card_removed_flag)
+          if (vr->any && vr->status == 0 && set_card_removed_flag)
             update_card_removed (idx, 1);
 
-          ss->any = 1;
+          vr->any = 1;
 
           /* Send a signal to all clients who applied for it.  */
           send_client_notifications ();
@@ -2330,8 +2354,9 @@ update_reader_status_file (int set_card_removed_flag)
             {
               /* FIXME: Use a real timeout.  */
               /* At least one connection and all allow a disconnect.  */
-              log_info ("disconnecting card in slot %d\n", ss->slot);
-              apdu_disconnect (ss->slot);
+              log_info ("disconnecting card in reader %d (%d)\n",
+                        idx, vr->slot);
+              apdu_disconnect (vr->slot);
             }
         }
 
@@ -2344,9 +2369,13 @@ update_reader_status_file (int set_card_removed_flag)
 void
 scd_update_reader_status_file (void)
 {
-  if (!pth_mutex_acquire (&status_file_update_lock, 1, NULL))
+  int err;
+  err = npth_mutex_lock (&status_file_update_lock);
+  if (err)
     return; /* locked - give up. */
   update_reader_status_file (1);
-  if (!pth_mutex_release (&status_file_update_lock))
-    log_error ("failed to release status_file_update lock\n");
+  err = npth_mutex_unlock (&status_file_update_lock);
+  if (err)
+    log_error ("failed to release status_file_update lock: %s\n",
+              strerror (err));
 }