Bump to 2.4.3
[platform/upstream/gpg2.git] / dirmngr / server.c
index 1b7e9e9..51a149c 100644 (file)
@@ -1,7 +1,8 @@
 /* server.c - LDAP and Keyserver access server
  * Copyright (C) 2002 Klarälvdalens Datakonsult AB
  * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2009, 2011, 2015 g10 Code GmbH
- * Copyright (C) 2014 Werner Koch
+ * Copyright (C) 2014, 2015, 2016 Werner Koch
+ * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik
  *
  * This file is part of GnuPG.
  *
@@ -16,7 +17,9 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, see <http://www.gnu.org/licenses/>.
+ * along with this program; if not, see <https://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: GPL-3.0+
  */
 
 #include <config.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <errno.h>
+#ifdef HAVE_W32_SYSTEM
+# ifndef WINVER
+#  define WINVER 0x0500  /* Same as in common/sysutils.c */
+# endif
+# include <winsock2.h>
+# include <sddl.h>
+#endif
 
 #include "dirmngr.h"
 #include <assuan.h>
 # include "ldap-wrapper.h"
 #endif
 #include "ks-action.h"
-#include "ks-engine.h"  /* (ks_hkp_print_hosttable) */
+#include "ks-engine.h"
 #if USE_LDAP
 # include "ldap-parse-uri.h"
 #endif
-#include "dns-cert.h"
-#include "mbox-util.h"
+#include "dns-stuff.h"
+#include "../common/mbox-util.h"
+#include "../common/zb32.h"
+#include "../common/server-help.h"
 
 /* To avoid DoS attacks we limit the size of a certificate to
-   something reasonable. */
-#define MAX_CERT_LENGTH (8*1024)
+   something reasonable.  The DoS was actually only an issue back when
+   Dirmngr was a system service and not a user service. */
+#define MAX_CERT_LENGTH (16*1024)
+
+/* The limit for the CERTLIST inquiry.  We allow for up to 20
+ * certificates but also take PEM encoding into account.  */
+#define MAX_CERTLIST_LENGTH ((MAX_CERT_LENGTH * 20 * 4)/3)
 
 /* The same goes for OpenPGP keyblocks, but here we need to allow for
    much longer blocks; a 200k keyblock is not too unusual for keys
-   with a lot of signatures (e.g. 0x5b0358a2).  */
-#define MAX_KEYBLOCK_LENGTH (512*1024)
+   with a lot of signatures (e.g. 0x5b0358a2).  9C31503C6D866396 even
+   has 770 KiB as of 2015-08-23.  To avoid adding a runtime option we
+   now use 20MiB which should really be enough.  Well, a key with
+   several pictures could be larger (the parser as a 18MiB limit for
+   attribute packets) but it won't be nice to the keyservers to send
+   them such large blobs.  */
+#define MAX_KEYBLOCK_LENGTH (20*1024*1024)
 
 
 #define PARM_ERROR(t) assuan_set_error (ctx, \
                                         gpg_error (GPG_ERR_ASS_PARAMETER), (t))
-#define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
+#define set_error(e,t) (ctx ? assuan_set_error (ctx, gpg_error (e), (t)) \
+                        /**/: gpg_error (e))
 
 
 
@@ -75,6 +98,9 @@ struct server_local_s
   /* Data used to associate an Assuan context with local server data */
   assuan_context_t assuan_ctx;
 
+  /* The session id (a counter).  */
+  unsigned int session_id;
+
   /* Per-session LDAP servers.  */
   ldap_server_t ldapservers;
 
@@ -84,12 +110,22 @@ struct server_local_s
   /* If this flag is set to true this dirmngr process will be
      terminated after the end of this session.  */
   int stopme;
+
+  /* State variable private to is_tor_running.  */
+  int tor_state;
+
+  /* If the first both flags are set the assuan logging of data lines
+   * is suppressed.  The count variable is used to show the number of
+   * non-logged bytes.  */
+  size_t inhibit_data_logging_count;
+  unsigned int inhibit_data_logging : 1;
+  unsigned int inhibit_data_logging_now : 1;
 };
 
 
 /* Cookie definition for assuan data line output.  */
-static ssize_t data_line_cookie_write (void *cookie,
-                                       const void *buffer, size_t size);
+static gpgrt_ssize_t data_line_cookie_write (void *cookie,
+                                             const void *buffer, size_t size);
 static int data_line_cookie_close (void *cookie);
 static es_cookie_io_functions_t data_line_cookie_functions =
   {
@@ -100,6 +136,9 @@ static es_cookie_io_functions_t data_line_cookie_functions =
   };
 
 
+/* Local prototypes */
+static const char *task_check_wkd_support (ctrl_t ctrl, const char *domain);
+
 
 
 \f
@@ -113,6 +152,18 @@ get_ldapservers_from_ctrl (ctrl_t ctrl)
     return NULL;
 }
 
+/* Release an uri_item_t list.  */
+void
+release_uri_item_list (uri_item_t list)
+{
+  while (list)
+    {
+      uri_item_t tmp = list->next;
+      http_release_parsed_uri (list->parsed_uri);
+      xfree (list);
+      list = tmp;
+    }
+}
 
 /* Release all configured keyserver info from CTRL.  */
 void
@@ -121,13 +172,8 @@ release_ctrl_keyservers (ctrl_t ctrl)
   if (! ctrl->server_local)
     return;
 
-  while (ctrl->server_local->keyservers)
-    {
-      uri_item_t tmp = ctrl->server_local->keyservers->next;
-      http_release_parsed_uri (ctrl->server_local->keyservers->parsed_uri);
-      xfree (ctrl->server_local->keyservers);
-      ctrl->server_local->keyservers = tmp;
-    }
+  release_uri_item_list (ctrl->server_local->keyservers);
+  ctrl->server_local->keyservers = NULL;
 }
 
 
@@ -157,9 +203,14 @@ leave_cmd (assuan_context_t ctx, gpg_error_t err)
 static gpg_error_t
 data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size)
 {
+  ctrl_t ctrl = assuan_get_pointer (ctx);
   const char *buffer = buffer_arg;
   gpg_error_t err;
 
+  /* If we do not want logging, enable it here.  */
+  if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging)
+    ctrl->server_local->inhibit_data_logging_now = 1;
+
   if (opt.verbose && buffer && size)
     {
       /* Ease reading of output by sending a physical line at each LF.  */
@@ -175,14 +226,14 @@ data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size)
           if (err)
             {
               gpg_err_set_errno (EIO);
-              return err;
+              goto leave;
             }
           buffer += n;
           nbytes -= n;
           if (nbytes && (err=assuan_send_data (ctx, NULL, 0))) /* Flush line. */
             {
               gpg_err_set_errno (EIO);
-              return err;
+              goto leave;
             }
         }
       while (nbytes);
@@ -193,24 +244,31 @@ data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size)
       if (err)
         {
           gpg_err_set_errno (EIO);  /* For use by data_line_cookie_write.  */
-          return err;
+          goto leave;
         }
     }
 
-  return 0;
+ leave:
+  if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging)
+    {
+      ctrl->server_local->inhibit_data_logging_now = 0;
+      ctrl->server_local->inhibit_data_logging_count += size;
+    }
+
+  return err;
 }
 
 
 /* A write handler used by es_fopencookie to write assuan data
    lines.  */
-static ssize_t
+static gpgrt_ssize_t
 data_line_cookie_write (void *cookie, const void *buffer, size_t size)
 {
   assuan_context_t ctx = cookie;
 
   if (data_line_write (ctx, buffer, size))
     return -1;
-  return (ssize_t)size;
+  return (gpgrt_ssize_t)size;
 }
 
 
@@ -219,6 +277,16 @@ data_line_cookie_close (void *cookie)
 {
   assuan_context_t ctx = cookie;
 
+  if (DBG_IPC)
+    {
+      ctrl_t ctrl = assuan_get_pointer (ctx);
+
+      if (ctrl && ctrl->server_local
+          && ctrl->server_local->inhibit_data_logging
+          && ctrl->server_local->inhibit_data_logging_count)
+        log_debug ("(%zu bytes sent via D lines not shown)\n",
+                   ctrl->server_local->inhibit_data_logging_count);
+    }
   if (assuan_send_data (ctx, NULL, 0))
     {
       gpg_err_set_errno (EIO);
@@ -256,75 +324,30 @@ strcpy_escaped_plus (char *d, const unsigned char *s)
 }
 
 
-/* Check whether the option NAME appears in LINE */
+/* This function returns true if a Tor server is running.  The status
+ * is cached for the current connection.  */
 static int
-has_option (const char *line, const char *name)
+is_tor_running (ctrl_t ctrl)
 {
-  const char *s;
-  int n = strlen (name);
-
-  s = strstr (line, name);
-  return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
-}
+  /* Check whether we can connect to the proxy.  */
 
-/* Same as has_option but only considers options at the begin of the
-   line.  This is useful for commands which allow arbitrary strings on
-   the line.  */
-static int
-has_leading_option (const char *line, const char *name)
-{
-  const char *s;
-  int n;
+  if (!ctrl || !ctrl->server_local)
+    return 0; /* Ooops.  */
 
-  if (name[0] != '-' || name[1] != '-' || !name[2] || spacep (name+2))
-    return 0;
-  n = strlen (name);
-  while ( *line == '-' && line[1] == '-' )
+  if (!ctrl->server_local->tor_state)
     {
-      s = line;
-      while (*line && !spacep (line))
-        line++;
-      if (n == (line - s) && !strncmp (s, name, n))
-        return 1;
-      while (spacep (line))
-        line++;
-    }
-  return 0;
-}
+      assuan_fd_t sock;
 
-
-/* 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
-   thhere 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; */
-/* } */
-
-
-/* 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++;
+      sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
+      if (sock == ASSUAN_INVALID_FD)
+        ctrl->server_local->tor_state = -1; /* Not running.  */
+      else
+        {
+          assuan_sock_close (sock);
+          ctrl->server_local->tor_state = 1; /* Running.  */
+        }
     }
-  return line;
+  return (ctrl->server_local->tor_state > 0);
 }
 
 
@@ -364,17 +387,15 @@ do_get_cert_local (ctrl_t ctrl, const char *name, const char *command)
   char *buf;
   ksba_cert_t cert;
 
-  if (name)
+  buf = name? strconcat (command, " ", name, NULL) : xtrystrdup (command);
+  if (!buf)
+    rc = gpg_error_from_syserror ();
+  else
     {
-      buf = xmalloc ( strlen (command) + 1 + strlen(name) + 1);
-      strcpy (stpcpy (stpcpy (buf, command), " "), name);
+      rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
+                           &value, &valuelen, MAX_CERT_LENGTH);
+      xfree (buf);
     }
-  else
-    buf = xstrdup (command);
-
-  rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
-                       &value, &valuelen, MAX_CERT_LENGTH);
-  xfree (buf);
   if (rc)
     {
       log_error (_("assuan_inquire(%s) failed: %s\n"),
@@ -404,12 +425,11 @@ do_get_cert_local (ctrl_t ctrl, const char *name, const char *command)
 
 
 
-/* Ask back to return a certificate for name, given as a regular
-   gpgsm certificate indentificates (e.g. fingerprint or one of the
-   other methods).  Alternatively, NULL may be used for NAME to
-   return the current target certificate. Either return the certificate
-   in a KSBA object or NULL if it is not available.
-*/
+/* Ask back to return a certificate for NAME, given as a regular gpgsm
+ * certificate identifier (e.g. fingerprint or one of the other
+ * methods).  Alternatively, NULL may be used for NAME to return the
+ * current target certificate.  Either return the certificate in a
+ * KSBA object or NULL if it is not available.  */
 ksba_cert_t
 get_cert_local (ctrl_t ctrl, const char *name)
 {
@@ -423,13 +443,12 @@ get_cert_local (ctrl_t ctrl, const char *name)
 
 }
 
-/* Ask back to return the issuing certificate for name, given as a
-   regular gpgsm certificate indentificates (e.g. fingerprint or one
-   of the other methods).  Alternatively, NULL may be used for NAME to
-   return thecurrent target certificate. Either return the certificate
-   in a KSBA object or NULL if it is not available.
 
-*/
+/* Ask back to return the issuing certificate for NAME, given as a
+ * regular gpgsm certificate identifier (e.g. fingerprint or one
+ * of the other methods).  Alternatively, NULL may be used for NAME to
+ * return the current target certificate. Either return the certificate
+ * in a KSBA object or NULL if it is not available.  */
 ksba_cert_t
 get_issuing_cert_local (ctrl_t ctrl, const char *name)
 {
@@ -442,8 +461,9 @@ get_issuing_cert_local (ctrl_t ctrl, const char *name)
   return do_get_cert_local (ctrl, name, "SENDISSUERCERT");
 }
 
+
 /* Ask back to return a certificate with subject NAME and a
  subjectKeyIdentifier of KEYID. */
* subjectKeyIdentifier of KEYID. */
 ksba_cert_t
 get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid)
 {
@@ -473,15 +493,13 @@ get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid)
       return NULL;
     }
 
-  buf = xtrymalloc (15 + strlen (hexkeyid) + 2 + strlen(name) + 1);
+  buf = strconcat ("SENDCERT_SKI ", hexkeyid, " /", name, NULL);
   if (!buf)
     {
-
       log_error ("can't allocate enough memory: %s\n", strerror (errno));
       xfree (hexkeyid);
       return NULL;
     }
-  strcpy (stpcpy (stpcpy (stpcpy (buf, "SENDCERT_SKI "), hexkeyid)," /"),name);
   xfree (hexkeyid);
 
   rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
@@ -620,6 +638,17 @@ option_handler (assuan_context_t ctx, const char *key, const char *value)
       else if (!(ctrl->http_proxy = xtrystrdup (value)))
         err = gpg_error_from_syserror ();
     }
+  else if (!strcmp (key, "honor-keyserver-url-used"))
+    {
+      /* Return an error if we are running in Tor mode.  */
+      if (dirmngr_use_tor ())
+        err = gpg_error (GPG_ERR_FORBIDDEN);
+    }
+  else if (!strcmp (key, "http-crl"))
+    {
+      int i = *value? atoi (value) : 0;
+      ctrl->http_no_crl = !i;
+    }
   else
     err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
 
@@ -631,20 +660,22 @@ option_handler (assuan_context_t ctx, const char *key, const char *value)
 static const char hlp_dns_cert[] =
   "DNS_CERT <subtype> <name>\n"
   "DNS_CERT --pka <user_id>\n"
+  "DNS_CERT --dane <user_id>\n"
   "\n"
   "Return the CERT record for <name>.  <subtype> is one of\n"
   "  *     Return the first record of any supported subtype\n"
   "  PGP   Return the first record of subtype PGP (3)\n"
   "  IPGP  Return the first record of subtype IPGP (6)\n"
-  "If the content of a certifciate is available (PGP) it is returned\n"
+  "If the content of a certificate is available (PGP) it is returned\n"
   "by data lines.  Fingerprints and URLs are returned via status lines.\n"
-  "In --pka mode the fingerprint and if available an URL is returned.";
+  "In --pka mode the fingerprint and if available an URL is returned.\n"
+  "In --dane mode the key is returned from RR type 61";
 static gpg_error_t
 cmd_dns_cert (assuan_context_t ctx, char *line)
 {
-  /* ctrl_t ctrl = assuan_get_pointer (ctx); */
+  ctrl_t ctrl = assuan_get_pointer (ctx);
   gpg_error_t err = 0;
-  int pka_mode;
+  int pka_mode, dane_mode;
   char *mbox = NULL;
   char *namebuf = NULL;
   char *encodedhash = NULL;
@@ -658,8 +689,16 @@ cmd_dns_cert (assuan_context_t ctx, char *line)
   char *url = NULL;
 
   pka_mode = has_option (line, "--pka");
+  dane_mode = has_option (line, "--dane");
   line = skip_options (line);
-  if (pka_mode)
+
+  if (pka_mode && dane_mode)
+    {
+      err = PARM_ERROR ("either --pka or --dane may be given");
+      goto leave;
+    }
+
+  if (pka_mode || dane_mode)
     ; /* No need to parse here - we do this later.  */
   else
     {
@@ -691,12 +730,15 @@ cmd_dns_cert (assuan_context_t ctx, char *line)
         }
     }
 
-  if (pka_mode)
+  if (pka_mode || dane_mode)
     {
-      char *domain;  /* Points to mbox.  */
-      char hashbuf[20];
+      char *domain;     /* Points to mbox.  */
+      char hashbuf[32]; /* For SHA-1 and SHA-256. */
 
-      mbox = mailbox_from_userid (line);
+      /* We lowercase ascii characters but the DANE I-D does not allow
+         this.  FIXME: Check after the release of the RFC whether to
+         change this.  */
+      mbox = mailbox_from_userid (line, 0);
       if (!mbox || !(domain = strchr (mbox, '@')))
         {
           err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id");
@@ -704,26 +746,50 @@ cmd_dns_cert (assuan_context_t ctx, char *line)
         }
       *domain++ = 0;
 
-      gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
-      encodedhash = zb32_encode (hashbuf, 8*20);
-      if (!encodedhash)
+      if (pka_mode)
         {
-          err = gpg_error_from_syserror ();
-          goto leave;
+          gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
+          encodedhash = zb32_encode (hashbuf, 8*20);
+          if (!encodedhash)
+            {
+              err = gpg_error_from_syserror ();
+              goto leave;
+            }
+          namebuf = strconcat (encodedhash, "._pka.", domain, NULL);
+          if (!namebuf)
+            {
+              err = gpg_error_from_syserror ();
+              goto leave;
+            }
+          name = namebuf;
+          certtype = DNS_CERTTYPE_IPGP;
         }
-      namebuf = strconcat (encodedhash, "._pka.", domain, NULL);
-      if (!namebuf)
+      else
         {
-          err = gpg_error_from_syserror ();
-          goto leave;
+          /* Note: The hash is truncated to 28 bytes and we lowercase
+             the result only for aesthetic reasons.  */
+          gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
+          encodedhash = bin2hex (hashbuf, 28, NULL);
+          if (!encodedhash)
+            {
+              err = gpg_error_from_syserror ();
+              goto leave;
+            }
+          ascii_strlwr (encodedhash);
+          namebuf = strconcat (encodedhash, "._openpgpkey.", domain, NULL);
+          if (!namebuf)
+            {
+              err = gpg_error_from_syserror ();
+              goto leave;
+            }
+          name = namebuf;
+          certtype = DNS_CERTTYPE_RR61;
         }
-      name = namebuf;
-      certtype = DNS_CERTTYPE_IPGP;
     }
   else
     name = line;
 
-  err = get_dns_cert (name, certtype, &key, &keylen, &fpr, &fprlen, &url);
+  err = get_dns_cert (ctrl, name, certtype, &key, &keylen, &fpr, &fprlen, &url);
   if (err)
     goto leave;
 
@@ -770,11 +836,331 @@ cmd_dns_cert (assuan_context_t ctx, char *line)
 
 
 \f
+/* Core of cmd_wkd_get and task_check_wkd_support.  If CTX is NULL
+ * this function will not write anything to the assuan output.  */
+static gpg_error_t
+proc_wkd_get (ctrl_t ctrl, assuan_context_t ctx, char *line)
+{
+  gpg_error_t err = 0;
+  char *mbox = NULL;
+  char *domainbuf = NULL;
+  char *domain;     /* Points to mbox or domainbuf.  This is used to
+                     * connect to the host.  */
+  char *domain_orig;/* Points to mbox.  This is the used for the
+                     * query; i.e. the domain part of the
+                     * addrspec.  */
+  char sha1buf[20];
+  char *uri = NULL;
+  char *encodedhash = NULL;
+  int opt_submission_addr;
+  int opt_policy_flags;
+  int is_wkd_query;   /* True if this is a real WKD query.  */
+  int no_log = 0;
+  char portstr[20] = { 0 };
+  int subdomain_mode = 0;
+
+  opt_submission_addr = has_option (line, "--submission-address");
+  opt_policy_flags = has_option (line, "--policy-flags");
+  if (has_option (line, "--quick"))
+    ctrl->timeout = opt.connect_quick_timeout;
+  line = skip_options (line);
+  is_wkd_query = !(opt_policy_flags || opt_submission_addr);
+
+  mbox = mailbox_from_userid (line, 0);
+  if (!mbox || !(domain = strchr (mbox, '@')))
+    {
+      err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id");
+      goto leave;
+    }
+  *domain++ = 0;
+  domain_orig = domain;
+
+
+  /* Let's check whether we already know that the domain does not
+   * support WKD.  */
+  if (is_wkd_query)
+    {
+      if (domaininfo_is_wkd_not_supported (domain_orig))
+        {
+          err = gpg_error (GPG_ERR_NO_DATA);
+          dirmngr_status_printf (ctrl, "NOTE", "wkd_cached_result %u", err);
+          goto leave;
+        }
+    }
+
+
+  /* First try the new "openpgp" subdomain.  We check that the domain
+   * is valid because it is later used as an unescaped filename part
+   * of the URI.  */
+  if (is_valid_domain_name (domain_orig))
+    {
+      dns_addrinfo_t aibuf;
+
+      domainbuf = strconcat ( "openpgpkey.", domain_orig, NULL);
+      if (!domainbuf)
+        {
+          err = gpg_error_from_syserror ();
+          goto leave;
+        }
+
+      /* FIXME: We should put a cache into dns-stuff because the same
+       * query (with a different port and socket type, though) will be
+       * done later by http function.  */
+      err = resolve_dns_name (ctrl, domainbuf, 0, 0, 0, &aibuf, NULL);
+      if (err)
+        {
+          err = 0;
+          xfree (domainbuf);
+          domainbuf = NULL;
+        }
+      else /* Got a subdomain. */
+        {
+          free_dns_addrinfo (aibuf);
+          subdomain_mode = 1;
+          domain = domainbuf;
+        }
+    }
+
+  /* Check for SRV records unless we have a subdomain. */
+  if (!subdomain_mode)
+    {
+      struct srventry *srvs;
+      unsigned int srvscount;
+      size_t domainlen, targetlen;
+      int i;
+
+      err = get_dns_srv (ctrl, domain, "openpgpkey", NULL, &srvs, &srvscount);
+      if (err)
+        {
+          /* Ignore server failed becuase there are too many resolvers
+           * which do not work as expected.  */
+          if (gpg_err_code (err) == GPG_ERR_SERVER_FAILED)
+            err = 0; /*(srvcount is guaranteed to be 0)*/
+          else
+            goto leave;
+        }
+
+      /* Check for rogue DNS names.  */
+      for (i = 0; i < srvscount; i++)
+        {
+          if (!is_valid_domain_name (srvs[i].target))
+            {
+              err = gpg_error (GPG_ERR_DNS_ADDRESS);
+              log_error ("rogue openpgpkey SRV record for '%s'\n", domain);
+              xfree (srvs);
+              goto leave;
+            }
+        }
+
+      /* Find the first target which also ends in DOMAIN or is equal
+       * to DOMAIN.  */
+      domainlen = strlen (domain);
+      for (i = 0; i < srvscount; i++)
+        {
+          if (DBG_DNS)
+            log_debug ("srv: trying '%s:%hu'\n", srvs[i].target, srvs[i].port);
+          targetlen = strlen (srvs[i].target);
+          if ((targetlen > domainlen + 1
+               && srvs[i].target[targetlen - domainlen - 1] == '.'
+               && !ascii_strcasecmp (srvs[i].target + targetlen - domainlen,
+                                     domain))
+              || (targetlen == domainlen
+                  && !ascii_strcasecmp (srvs[i].target, domain)))
+            {
+              /* found.  */
+              domainbuf = xtrystrdup (srvs[i].target);
+              if (!domainbuf)
+                {
+                  err = gpg_error_from_syserror ();
+                  xfree (srvs);
+                  goto leave;
+                }
+              domain = domainbuf;
+              if (srvs[i].port)
+                snprintf (portstr, sizeof portstr, ":%hu", srvs[i].port);
+              break;
+            }
+        }
+      xfree (srvs);
+    }
+
+  /* Prepare the hash of the local part.  */
+  gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, mbox, strlen (mbox));
+  encodedhash = zb32_encode (sha1buf, 8*20);
+  if (!encodedhash)
+    {
+      err = gpg_error_from_syserror ();
+      goto leave;
+    }
+
+  if (opt_submission_addr)
+    {
+      uri = strconcat ("https://",
+                       domain,
+                       portstr,
+                       "/.well-known/openpgpkey/",
+                       subdomain_mode? domain_orig : "",
+                       subdomain_mode? "/" : "",
+                       "submission-address",
+                       NULL);
+    }
+  else if (opt_policy_flags)
+    {
+      uri = strconcat ("https://",
+                       domain,
+                       portstr,
+                       "/.well-known/openpgpkey/",
+                       subdomain_mode? domain_orig : "",
+                       subdomain_mode? "/" : "",
+                       "policy",
+                       NULL);
+    }
+  else
+    {
+      char *escapedmbox;
+
+      escapedmbox = http_escape_string (mbox, "%;?&=+#");
+      if (escapedmbox)
+        {
+          uri = strconcat ("https://",
+                           domain,
+                           portstr,
+                           "/.well-known/openpgpkey/",
+                           subdomain_mode? domain_orig : "",
+                           subdomain_mode? "/" : "",
+                           "hu/",
+                           encodedhash,
+                           "?l=",
+                           escapedmbox,
+                           NULL);
+          xfree (escapedmbox);
+          no_log = 1;
+          if (uri)
+            {
+              err = dirmngr_status_printf (ctrl, "SOURCE", "https://%s%s",
+                                           domain, portstr);
+              if (err)
+                goto leave;
+            }
+        }
+    }
+  if (!uri)
+    {
+      err = gpg_error_from_syserror ();
+      goto leave;
+    }
+
+  /* Setup an output stream and perform the get.  */
+  {
+    estream_t outfp;
+
+    outfp = ctx? es_fopencookie (ctx, "w", data_line_cookie_functions) : NULL;
+    if (!outfp && ctx)
+      err = set_error (GPG_ERR_ASS_GENERAL,
+                       "error setting up a data stream");
+    else
+      {
+        if (ctrl->server_local)
+          {
+            if (no_log)
+              ctrl->server_local->inhibit_data_logging = 1;
+            ctrl->server_local->inhibit_data_logging_now = 0;
+            ctrl->server_local->inhibit_data_logging_count = 0;
+          }
+        err = ks_action_fetch (ctrl, uri, outfp);
+        es_fclose (outfp);
+        if (ctrl->server_local)
+          ctrl->server_local->inhibit_data_logging = 0;
+
+        /* Register the result under the domain name of MBOX. */
+        switch (gpg_err_code (err))
+          {
+          case 0:
+            domaininfo_set_wkd_supported (domain_orig);
+            break;
+
+          case GPG_ERR_NO_NAME:
+            /* There is no such domain.  */
+            domaininfo_set_no_name (domain_orig);
+            break;
+
+          case GPG_ERR_NO_DATA:
+            if (is_wkd_query && ctrl->server_local)
+              {
+                /* Mark that and schedule a check.  */
+                domaininfo_set_wkd_not_found (domain_orig);
+                workqueue_add_task (task_check_wkd_support, domain_orig,
+                                    ctrl->server_local->session_id, 1);
+              }
+            else if (opt_policy_flags) /* No policy file - no support.  */
+              domaininfo_set_wkd_not_supported (domain_orig);
+            break;
+
+          default:
+            /* Don't register other errors.  */
+            break;
+          }
+      }
+  }
+
+ leave:
+  xfree (uri);
+  xfree (encodedhash);
+  xfree (mbox);
+  xfree (domainbuf);
+  return err;
+}
+
+
+static const char hlp_wkd_get[] =
+  "WKD_GET [--submission-address|--policy-flags] <user_id>\n"
+  "\n"
+  "Return the key or other info for <user_id>\n"
+  "from the Web Key Directory.";
+static gpg_error_t
+cmd_wkd_get (assuan_context_t ctx, char *line)
+{
+  ctrl_t ctrl = assuan_get_pointer (ctx);
+  gpg_error_t err;
+
+  err = proc_wkd_get (ctrl, ctx, line);
+
+  return leave_cmd (ctx, err);
+}
+
+
+/* A task to check whether DOMAIN supports WKD.  This is done by
+ * checking whether the policy flags file can be read.  */
+static const char *
+task_check_wkd_support (ctrl_t ctrl, const char *domain)
+{
+  char *string;
+
+  if (!ctrl || !domain)
+    return "check_wkd_support";
+
+  string = strconcat ("--policy-flags foo@", domain, NULL);
+  if (!string)
+    log_error ("%s: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ()));
+  else
+    {
+      proc_wkd_get (ctrl, NULL, string);
+      xfree (string);
+    }
+
+  return NULL;
+}
+
+
+\f
 static const char hlp_ldapserver[] =
-  "LDAPSERVER <data>\n"
+  "LDAPSERVER [--clear] <data>\n"
   "\n"
   "Add a new LDAP server to the list of configured LDAP servers.\n"
-  "DATA is in the same format as expected in the configure file.";
+  "DATA is in the same format as expected in the configure file.\n"
+  "An optional prefix \"ldap:\" is allowed.  With no args all\n"
+  "configured ldapservers are listed.  Option --clear removes all\n"
+  "servers configured in this session.";
 static gpg_error_t
 cmd_ldapserver (assuan_context_t ctx, char *line)
 {
@@ -782,13 +1168,63 @@ cmd_ldapserver (assuan_context_t ctx, char *line)
   ctrl_t ctrl = assuan_get_pointer (ctx);
   ldap_server_t server;
   ldap_server_t *last_next_p;
+  int clear_flag;
 
+  clear_flag = has_option (line, "--clear");
+  line = skip_options (line);
   while (spacep (line))
     line++;
-  if (*line == '\0')
-    return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing")));
 
-  server = ldapserver_parse_one (line, "", 0);
+  if (clear_flag)
+    {
+#if USE_LDAP
+      ldapserver_list_free (ctrl->server_local->ldapservers);
+#endif /*USE_LDAP*/
+      ctrl->server_local->ldapservers = NULL;
+    }
+
+  if (!*line && clear_flag)
+    return leave_cmd (ctx, 0);
+
+  if (!*line)
+    {
+      /* List all ldapservers.  */
+      struct ldapserver_iter ldapserver_iter;
+      char *tmpstr;
+      char portstr[20];
+
+      for (ldapserver_iter_begin (&ldapserver_iter, ctrl);
+           !ldapserver_iter_end_p (&ldapserver_iter);
+           ldapserver_iter_next (&ldapserver_iter))
+        {
+          server = ldapserver_iter.server;
+          if (server->port)
+            snprintf (portstr, sizeof portstr, "%d", server->port);
+          else
+            *portstr = 0;
+
+          tmpstr = xtryasprintf ("ldap:%s:%s:%s:%s:%s:%s%s:",
+                                 server->host? server->host : "",
+                                 portstr,
+                                 server->user? server->user : "",
+                                 server->pass? "*****": "",
+                                 server->base? server->base : "",
+                                 server->starttls ? "starttls" :
+                                 server->ldap_over_tls ? "ldaptls" : "none",
+                                 server->ntds ? ",ntds" : "");
+          if (!tmpstr)
+            return leave_cmd (ctx, gpg_error_from_syserror ());
+          dirmngr_status (ctrl, "LDAPSERVER", tmpstr, NULL);
+          xfree (tmpstr);
+        }
+      return leave_cmd (ctx, 0);
+    }
+
+  /* Skip an "ldap:" prefix unless it is a valid ldap url.  */
+  if (!strncmp (line, "ldap:", 5) && !(line[5] == '/' && line[6] == '/'))
+    line += 5;
+
+  server = ldapserver_parse_one (line, NULL, 0);
   if (! server)
     return leave_cmd (ctx, gpg_error (GPG_ERR_INV_ARG));
 
@@ -806,7 +1242,7 @@ cmd_ldapserver (assuan_context_t ctx, char *line)
 
 static const char hlp_isvalid[] =
   "ISVALID [--only-ocsp] [--force-default-responder]"
-  " <certificate_id>|<certificate_fpr>\n"
+  " <certificate_id> [<certificate_fpr>]\n"
   "\n"
   "This command checks whether the certificate identified by the\n"
   "certificate_id is valid.  This is done by consulting CRLs or\n"
@@ -818,8 +1254,9 @@ static const char hlp_isvalid[] =
   "delimited by a single dot.  The first part is the SHA-1 hash of the\n"
   "issuer name and the second part the serial number.\n"
   "\n"
-  "Alternatively the certificate's fingerprint may be given in which\n"
-  "case an OCSP request is done before consulting the CRL.\n"
+  "If an OCSP check is desired CERTIFICATE_FPR with the hex encoded\n"
+  "fingerprint of the certificate is required.  In this case an OCSP\n"
+  "request is done before consulting the CRL.\n"
   "\n"
   "If the option --only-ocsp is given, no fallback to a CRL check will\n"
   "be used.\n"
@@ -831,7 +1268,7 @@ static gpg_error_t
 cmd_isvalid (assuan_context_t ctx, char *line)
 {
   ctrl_t ctrl = assuan_get_pointer (ctx);
-  char *issuerhash, *serialno;
+  char *issuerhash, *serialno, *fpr;
   gpg_error_t err;
   int did_inquire = 0;
   int ocsp_mode = 0;
@@ -842,25 +1279,36 @@ cmd_isvalid (assuan_context_t ctx, char *line)
   force_default_responder = has_option (line, "--force-default-responder");
   line = skip_options (line);
 
-  issuerhash = xstrdup (line); /* We need to work on a copy of the
-                                  line because that same Assuan
-                                  context may be used for an inquiry.
-                                  That is because Assuan reuses its
-                                  line buffer.
-                                   */
+  /* We need to work on a copy of the line because that same Assuan
+   * context may be used for an inquiry.  That is because Assuan
+   * reuses its line buffer.  */
+  issuerhash = xstrdup (line);
 
   serialno = strchr (issuerhash, '.');
-  if (serialno)
-    *serialno++ = 0;
-  else
+  if (!serialno)
+    {
+      xfree (issuerhash);
+      return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID")));
+    }
+  *serialno++ = 0;
+  if (strlen (issuerhash) != 40)
+    {
+      xfree (issuerhash);
+      return leave_cmd (ctx, PARM_ERROR ("cert ID is too short"));
+    }
+
+  fpr = strchr (serialno, ' ');
+  while (fpr && spacep (fpr))
+    fpr++;
+  if (fpr && *fpr)
     {
-      char *endp = strchr (issuerhash, ' ');
+      char *endp = strchr (fpr, ' ');
       if (endp)
         *endp = 0;
-      if (strlen (issuerhash) != 40)
+      if (strlen (fpr) != 40)
         {
           xfree (issuerhash);
-          return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID")));
+          return leave_cmd (ctx, PARM_ERROR ("fingerprint too short"));
         }
       ocsp_mode = 1;
     }
@@ -869,20 +1317,39 @@ cmd_isvalid (assuan_context_t ctx, char *line)
  again:
   if (ocsp_mode)
     {
-      /* Note, that we ignore the given issuer hash and instead rely
-         on the current certificate semantics used with this
-         command. */
+      gnupg_isotime_t revoked_at;
+      const char *reason;
+
+      /* Note, that we currently ignore the supplied fingerprint FPR;
+       * instead ocsp_isvalid does an inquire to ask for the cert.
+       * The fingerprint may eventually be used to lookup the
+       * certificate in a local cache.  */
       if (!opt.allow_ocsp)
         err = gpg_error (GPG_ERR_NOT_SUPPORTED);
       else
-        err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder);
-      /* Fixme: If we got no ocsp response and --only-ocsp is not used
-         we should fall back to CRL mode.  Thus we need to clear
-         OCSP_MODE, get the issuerhash and the serialno from the
-         current certificate and jump to again. */
+        err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder,
+                            revoked_at, &reason);
+
+      if (gpg_err_code (err) == GPG_ERR_CERT_REVOKED)
+        dirmngr_status_printf (ctrl, "REVOCATIONINFO", "%s %s",
+                               revoked_at, reason);
+
+      if (gpg_err_code (err) == GPG_ERR_CONFIGURATION
+          && gpg_err_source (err) == GPG_ERR_SOURCE_DIRMNGR)
+        {
+          /* No default responder configured - fallback to CRL.  */
+          if (!only_ocsp)
+            log_info ("falling back to CRL check\n");
+          ocsp_mode = 0;
+          goto again;
+        }
     }
   else if (only_ocsp)
     err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
+  else if (opt.fake_crl && (err = fakecrl_isvalid (ctrl, issuerhash, serialno)))
+    {
+      /* We already got the error code.  */
+    }
   else
     {
       switch (crl_cache_isvalid (ctrl,
@@ -904,8 +1371,11 @@ cmd_isvalid (assuan_context_t ctx, char *line)
               goto again;
             }
           break;
+        case CRL_CACHE_NOTTRUSTED:
+          err = gpg_error (GPG_ERR_NOT_TRUSTED);
+          break;
         case CRL_CACHE_CANTUSE:
-          err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
+          err = gpg_error (GPG_ERR_INV_CRL_OBJ);
           break;
         default:
           log_fatal ("crl_cache_isvalid returned invalid code\n");
@@ -918,7 +1388,7 @@ cmd_isvalid (assuan_context_t ctx, char *line)
 
 
 /* If the line contains a SHA-1 fingerprint as the first argument,
-   return the FPR vuffer on success.  The function checks that the
+   return the FPR buffer on success.  The function checks that the
    fingerprint consists of valid characters and prints and error
    message if it does not and returns NULL.  Fingerprints are
    considered optional and thus no explicit error is returned. NULL is
@@ -1013,7 +1483,7 @@ cmd_checkcrl (assuan_context_t ctx, char *line)
         goto leave;
     }
 
-  assert (cert);
+  log_assert (cert);
 
   err = crl_cache_cert_isvalid (ctrl, cert, ctrl->force_crl_refresh);
   if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN)
@@ -1048,7 +1518,7 @@ static const char hlp_checkocsp[] =
   "Processing then takes place without further interaction; in\n"
   "particular dirmngr tries to locate other required certificates by\n"
   "its own mechanism which includes a local certificate store as well\n"
-  "as a list of trusted root certifciates.\n"
+  "as a list of trusted root certificates.\n"
   "\n"
   "If the option --force-default-responder is given, only the default\n"
   "OCSP responder will be used and any other methods of obtaining an\n"
@@ -1064,6 +1534,8 @@ cmd_checkocsp (assuan_context_t ctx, char *line)
   unsigned char fprbuffer[20], *fpr;
   ksba_cert_t cert;
   int force_default_responder;
+  gnupg_isotime_t revoked_at;
+  const char *reason;
 
   force_default_responder = has_option (line, "--force-default-responder");
   line = skip_options (line);
@@ -1099,12 +1571,18 @@ cmd_checkocsp (assuan_context_t ctx, char *line)
         goto leave;
     }
 
-  assert (cert);
+  log_assert (cert);
 
   if (!opt.allow_ocsp)
     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
   else
-    err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder);
+    err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder,
+                        revoked_at, &reason);
+
+  if (gpg_err_code (err) == GPG_ERR_CERT_REVOKED)
+    dirmngr_status_printf (ctrl, "REVOCATIONINFO", "%s %s",
+                           revoked_at, reason);
+
 
  leave:
   ksba_cert_release (cert);
@@ -1217,7 +1695,7 @@ lookup_cert_by_pattern (assuan_context_t ctx, char *line,
         }
     }
 
-  /* First look through the internal cache.  The certifcates retruned
+  /* First look through the internal cache.  The certificates returned
      here are not counted towards the truncation limit.  */
   if (single && !cache_only)
     ; /* Do not read from the local cache in this case.  */
@@ -1231,7 +1709,8 @@ lookup_cert_by_pattern (assuan_context_t ctx, char *line,
           if (!err && single)
             goto ready;
 
-          if (gpg_err_code (err) == GPG_ERR_NO_DATA)
+          if (gpg_err_code (err) == GPG_ERR_NO_DATA
+              || gpg_err_code (err) == GPG_ERR_NOT_FOUND)
             {
               err = 0;
               if (cache_only)
@@ -1543,7 +2022,7 @@ cmd_cachecert (assuan_context_t ctx, char *line)
 
 
 static const char hlp_validate[] =
-  "VALIDATE\n"
+  "VALIDATE [--systrust] [--tls] [--no-crl]\n"
   "\n"
   "Validate a certificate using the certificate validation function\n"
   "used internally by dirmngr.  This command is only useful for\n"
@@ -1553,20 +2032,40 @@ static const char hlp_validate[] =
   "  INQUIRE TARGETCERT\n"
   "\n"
   "and the caller is expected to return the certificate for the\n"
-  "request as a binary blob.";
+  "request as a binary blob.  The option --tls modifies this by asking\n"
+  "for list of certificates with\n"
+  "\n"
+  "  INQUIRE CERTLIST\n"
+  "\n"
+  "Here the first certificate is the target certificate, the remaining\n"
+  "certificates are suggested intermediary certificates.  All certificates\n"
+  "need to be PEM encoded.\n"
+  "\n"
+  "The option --systrust changes the behaviour to include the system\n"
+  "provided root certificates as trust anchors.  The option --no-crl\n"
+  "skips CRL checks";
 static gpg_error_t
 cmd_validate (assuan_context_t ctx, char *line)
 {
   ctrl_t ctrl = assuan_get_pointer (ctx);
   gpg_error_t err;
   ksba_cert_t cert = NULL;
+  certlist_t certlist = NULL;
   unsigned char *value = NULL;
   size_t valuelen;
+  int systrust_mode, tls_mode, no_crl;
 
-  (void)line;
+  systrust_mode = has_option (line, "--systrust");
+  tls_mode = has_option (line, "--tls");
+  no_crl = has_option (line, "--no-crl");
+  line = skip_options (line);
 
-  err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
-                       &value, &valuelen, MAX_CERT_LENGTH);
+  if (tls_mode)
+    err = assuan_inquire (ctrl->server_local->assuan_ctx, "CERTLIST",
+                          &value, &valuelen, MAX_CERTLIST_LENGTH);
+  else
+    err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
+                          &value, &valuelen, MAX_CERT_LENGTH);
   if (err)
     {
       log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
@@ -1575,40 +2074,207 @@ cmd_validate (assuan_context_t ctx, char *line)
 
   if (!valuelen) /* No data returned; return a comprehensible error. */
     err = gpg_error (GPG_ERR_MISSING_CERT);
-  else
+  else if (tls_mode)
     {
-      err = ksba_cert_new (&cert);
-      if (!err)
+      estream_t fp;
+
+      fp = es_fopenmem_init (0, "rb", value, valuelen);
+      if (!fp)
+        err = gpg_error_from_syserror ();
+      else
+        {
+          err = read_certlist_from_stream (&certlist, fp);
+          es_fclose (fp);
+          if (!err && !certlist)
+            err = gpg_error (GPG_ERR_MISSING_CERT);
+          if (!err)
+            {
+              /* Extract the first certificate from the list.  */
+              cert = certlist->cert;
+              ksba_cert_ref (cert);
+            }
+        }
+    }
+  else
+    {
+      err = ksba_cert_new (&cert);
+      if (!err)
         err = ksba_cert_init_from_mem (cert, value, valuelen);
     }
   xfree (value);
   if(err)
     goto leave;
 
-  /* If we have this certificate already in our cache, use the cached
-     version for validation because this will take care of any cached
-     results. */
-  {
-    unsigned char fpr[20];
-    ksba_cert_t tmpcert;
+  if (!tls_mode)
+    {
+      /* If we have this certificate already in our cache, use the
+       * cached version for validation because this will take care of
+       * any cached results.  We don't need to do this in tls mode
+       * because this has already been done for certificate in a
+       * certlist_t. */
+      unsigned char fpr[20];
+      ksba_cert_t tmpcert;
 
-    cert_compute_fpr (cert, fpr);
-    tmpcert = get_cert_byfpr (fpr);
-    if (tmpcert)
-      {
-        ksba_cert_release (cert);
-        cert = tmpcert;
-      }
-  }
+      cert_compute_fpr (cert, fpr);
+      tmpcert = get_cert_byfpr (fpr);
+      if (tmpcert)
+        {
+          ksba_cert_release (cert);
+          cert = tmpcert;
+        }
+    }
+
+  /* Quick hack to make verification work by inserting the supplied
+   * certs into the cache.  */
+  if (tls_mode && certlist)
+    {
+      certlist_t cl;
 
-  err = validate_cert_chain (ctrl, cert, NULL, VALIDATE_MODE_CERT, NULL);
+      for (cl = certlist->next; cl; cl = cl->next)
+        cache_cert (cl->cert);
+    }
+
+  err = validate_cert_chain (ctrl, cert, NULL,
+                             (VALIDATE_FLAG_TRUST_CONFIG
+                              | (tls_mode ? VALIDATE_FLAG_TLS : 0)
+                              | (systrust_mode ? VALIDATE_FLAG_TRUST_SYSTEM : 0)
+                              | (no_crl ? VALIDATE_FLAG_NOCRLCHECK : 0)),
+                             NULL);
 
  leave:
   ksba_cert_release (cert);
+  release_certlist (certlist);
   return leave_cmd (ctx, err);
 }
 
+
 \f
+/* Parse an keyserver URI and store it in a new uri item which is
+   returned at R_ITEM.  On error return an error code.  */
+static gpg_error_t
+make_keyserver_item (const char *uri, uri_item_t *r_item)
+{
+  /* We used to have DNS CNAME redirection from the URLs below to
+   * sks-keyserver. pools.  The idea was to allow for a quick way to
+   * switch to a different set of pools.  The problem with that
+   * approach is that TLS needs to verify the hostname and - because
+   * DNS is not secured - it can only check the user supplied hostname
+   * and not a hostname from a CNAME RR.  Thus the final server all
+   * need to have certificates with the actual pool name as well as
+   * for keys.gnupg.net - that would render the advantage of
+   * keys.gnupg.net useless and so we better give up on this.  Because
+   * the keys.gnupg.net URL are still in widespread use we do a static
+   * mapping here.
+   */
+  if (!strcmp (uri, "hkps://keys.gnupg.net")
+      || !strcmp (uri, "keys.gnupg.net"))
+    uri = "hkps://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "https://keys.gnupg.net"))
+    uri = "hkps://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "hkp://keys.gnupg.net"))
+    uri = "hkp://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "http://keys.gnupg.net"))
+    uri = "hkp://keyserver.ubuntu.com:80";
+  else if (!strcmp (uri, "hkps://http-keys.gnupg.net")
+           || !strcmp (uri, "http-keys.gnupg.net"))
+    uri = "hkps://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "https://http-keys.gnupg.net"))
+    uri = "hkps://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "hkp://http-keys.gnupg.net"))
+    uri = "hkp://keyserver.ubuntu.com";
+  else if (!strcmp (uri, "http://http-keys.gnupg.net"))
+    uri = "hkp://keyserver.ubuntu.com:80";
+
+  return ks_action_parse_uri (uri, r_item);
+}
+
+
+/* If no keyserver is stored in CTRL but a global keyserver has been
+   set, put that global keyserver into CTRL.  We need use this
+   function to help migrate from the old gpg based keyserver
+   configuration to the new dirmngr based configuration.  */
+static gpg_error_t
+ensure_keyserver (ctrl_t ctrl)
+{
+  gpg_error_t err;
+  uri_item_t item;
+  uri_item_t onion_items = NULL;
+  uri_item_t plain_items = NULL;
+  uri_item_t ui;
+  strlist_t sl;
+
+  if (ctrl->server_local->keyservers)
+    return 0; /* Already set for this session.  */
+  if (!opt.keyserver)
+    {
+      /* No global option set.  Fall back to default:  */
+      return make_keyserver_item (DIRMNGR_DEFAULT_KEYSERVER,
+                                  &ctrl->server_local->keyservers);
+    }
+
+  for (sl = opt.keyserver; sl; sl = sl->next)
+    {
+      err = make_keyserver_item (sl->d, &item);
+      if (err)
+        goto leave;
+      if (item->parsed_uri->onion)
+        {
+          item->next = onion_items;
+          onion_items = item;
+        }
+      else
+        {
+          item->next = plain_items;
+          plain_items = item;
+        }
+    }
+
+  /* Decide which to use.  Note that the session has no keyservers
+     yet set. */
+  if (onion_items && !onion_items->next && plain_items && !plain_items->next)
+    {
+      /* If there is just one onion and one plain keyserver given, we take
+         only one depending on whether Tor is running or not.  */
+      if (!dirmngr_never_use_tor_p () && is_tor_running (ctrl))
+        {
+          ctrl->server_local->keyservers = onion_items;
+          onion_items = NULL;
+        }
+      else
+        {
+          ctrl->server_local->keyservers = plain_items;
+          plain_items = NULL;
+        }
+    }
+  else if (dirmngr_never_use_tor_p () || !is_tor_running (ctrl))
+    {
+      /* Tor is not running.  It does not make sense to add Onion
+         addresses.  */
+      ctrl->server_local->keyservers = plain_items;
+      plain_items = NULL;
+    }
+  else
+    {
+      /* In all other cases add all keyservers.  */
+      ctrl->server_local->keyservers = onion_items;
+      onion_items = NULL;
+      for (ui = ctrl->server_local->keyservers; ui && ui->next; ui = ui->next)
+        ;
+      if (ui)
+        ui->next = plain_items;
+      else
+        ctrl->server_local->keyservers = plain_items;
+      plain_items = NULL;
+    }
+
+ leave:
+  release_uri_item_list (onion_items);
+  release_uri_item_list (plain_items);
+
+  return err;
+}
+
+
 static const char hlp_keyserver[] =
   "KEYSERVER [<options>] [<uri>|<host>]\n"
   "Options are:\n"
@@ -1653,6 +2319,13 @@ cmd_keyserver (assuan_context_t ctx, char *line)
 
   if (resolve_flag)
     {
+      err = ensure_keyserver (ctrl);
+      if (err)
+        {
+          assuan_set_error (ctx, err,
+                            "Bad keyserver configuration in dirmngr.conf");
+          goto leave;
+        }
       err = ks_action_resolve (ctrl, ctrl->server_local->keyservers);
       if (err)
         goto leave;
@@ -1693,29 +2366,9 @@ cmd_keyserver (assuan_context_t ctx, char *line)
 
   if (add_flag)
     {
-      item = xtrymalloc (sizeof *item + strlen (line));
-      if (!item)
-        {
-          err = gpg_error_from_syserror ();
-          goto leave;
-        }
-      item->next = NULL;
-      item->parsed_uri = NULL;
-      strcpy (item->uri, line);
-
-#if USE_LDAP
-      if (ldap_uri_p (item->uri))
-       err = ldap_parse_uri (&item->parsed_uri, line);
-      else
-#endif
-       {
-         err = http_parse_uri (&item->parsed_uri, line, 1);
-       }
+      err = make_keyserver_item (line, &item);
       if (err)
-        {
-          xfree (item);
-          goto leave;
-        }
+        goto leave;
     }
   if (clear_flag)
     release_ctrl_keyservers (ctrl);
@@ -1725,10 +2378,20 @@ cmd_keyserver (assuan_context_t ctx, char *line)
       ctrl->server_local->keyservers = item;
     }
 
-  if (!add_flag && !clear_flag && !help_flag) /* List configured keyservers.  */
+  if (!add_flag && !clear_flag && !help_flag)
     {
+      /* List configured keyservers.  However, we first add a global
+         keyserver. */
       uri_item_t u;
 
+      err = ensure_keyserver (ctrl);
+      if (err)
+        {
+          assuan_set_error (ctx, err,
+                            "Bad keyserver configuration in dirmngr.conf");
+          goto leave;
+        }
+
       for (u=ctrl->server_local->keyservers; u; u = u->next)
         dirmngr_status (ctrl, "KEYSERVER", u->uri, NULL);
     }
@@ -1754,7 +2417,8 @@ cmd_ks_search (assuan_context_t ctx, char *line)
   char *p;
   estream_t outfp;
 
-  /* No options for now.  */
+  if (has_option (line, "--quick"))
+    ctrl->timeout = opt.connect_quick_timeout;
   line = skip_options (line);
 
   /* Break the line down into an strlist.  Each pattern is
@@ -1781,6 +2445,10 @@ cmd_ks_search (assuan_context_t ctx, char *line)
         }
     }
 
+  err = ensure_keyserver (ctrl);
+  if (err)
+    goto leave;
+
   /* Setup an output stream and perform the search.  */
   outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
   if (!outfp)
@@ -1800,28 +2468,49 @@ cmd_ks_search (assuan_context_t ctx, char *line)
 
 \f
 static const char hlp_ks_get[] =
-  "KS_GET {<pattern>}\n"
+  "KS_GET [--quick] [--newer=TIME] [--ldap] [--first|--next] {<pattern>}\n"
   "\n"
   "Get the keys matching PATTERN from the configured OpenPGP keyservers\n"
   "(see command KEYSERVER).  Each pattern should be a keyid, a fingerprint,\n"
-  "or an exact name indicated by the '=' prefix.";
+  "or an exact name indicated by the '=' prefix.  Option --quick uses a\n"
+  "shorter timeout; --ldap will use only ldap servers.  With --first only\n"
+  "the first item is returned; --next is used to return the next item\n"
+  "Option --newer works only with certain LDAP servers.";
 static gpg_error_t
 cmd_ks_get (assuan_context_t ctx, char *line)
 {
   ctrl_t ctrl = assuan_get_pointer (ctx);
   gpg_error_t err;
-  strlist_t list, sl;
+  strlist_t list = NULL;
+  strlist_t sl;
+  const char *s;
   char *p;
   estream_t outfp;
-
-  /* No options for now.  */
+  unsigned int flags = 0;
+  gnupg_isotime_t opt_newer;
+
+  *opt_newer = 0;
+
+  if (has_option (line, "--quick"))
+    ctrl->timeout = opt.connect_quick_timeout;
+  if (has_option (line, "--ldap"))
+    flags |= KS_GET_FLAG_ONLY_LDAP;
+  if (has_option (line, "--first"))
+    flags |= KS_GET_FLAG_FIRST;
+  if (has_option (line, "--next"))
+    flags |= KS_GET_FLAG_NEXT;
+  if ((s = option_value (line, "--newer"))
+      && !string2isotime (opt_newer, s))
+    {
+      err = set_error (GPG_ERR_SYNTAX, "invalid time format");
+      goto leave;
+    }
   line = skip_options (line);
 
   /* Break the line into a strlist.  Each pattern is by
      definition percent-plus escaped.  However we only support keyids
      and fingerprints and thus the client has no need to apply the
      escaping.  */
-  list = NULL;
   for (p=line; *p; line = p)
     {
       while (*p && *p != ' ')
@@ -1843,14 +2532,64 @@ cmd_ks_get (assuan_context_t ctx, char *line)
         }
     }
 
+  if ((flags & KS_GET_FLAG_FIRST) && !(flags & KS_GET_FLAG_ONLY_LDAP))
+    {
+      err = PARM_ERROR ("--first is only supported with --ldap");
+      goto leave;
+    }
+
+  if (list && list->next && (flags & KS_GET_FLAG_FIRST))
+    {
+      /* ks_action_get loops over the pattern and we can't easily keep
+       * this state.  */
+      err = PARM_ERROR ("Only one pattern allowed with --first");
+      goto leave;
+    }
+
+  if (!list && (flags & KS_GET_FLAG_FIRST))
+    {
+      /* Need to add a dummy pattern if no pattern is given.  */
+      if (!add_to_strlist_try (&list, ""))
+        {
+          err = gpg_error_from_syserror ();
+          goto leave;
+        }
+    }
+
+
+  if ((flags & KS_GET_FLAG_NEXT))
+    {
+      if (list || (flags & ~KS_GET_FLAG_NEXT))
+        {
+          err = PARM_ERROR ("No pattern or other options allowed with --next");
+          goto leave;
+        }
+      /* Add a dummy pattern.  */
+      if (!add_to_strlist_try (&list, ""))
+        {
+          err = gpg_error_from_syserror ();
+          goto leave;
+        }
+    }
+
+
+  err = ensure_keyserver (ctrl);
+  if (err)
+    goto leave;
+
   /* Setup an output stream and perform the get.  */
   outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
   if (!outfp)
     err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
   else
     {
-      err = ks_action_get (ctrl, ctrl->server_local->keyservers, list, outfp);
+      ctrl->server_local->inhibit_data_logging = 1;
+      ctrl->server_local->inhibit_data_logging_now = 0;
+      ctrl->server_local->inhibit_data_logging_count = 0;
+      err = ks_action_get (ctrl, ctrl->server_local->keyservers,
+                           list, flags, opt_newer, outfp);
       es_fclose (outfp);
+      ctrl->server_local->inhibit_data_logging = 0;
     }
 
  leave:
@@ -1870,19 +2609,29 @@ cmd_ks_fetch (assuan_context_t ctx, char *line)
   gpg_error_t err;
   estream_t outfp;
 
-  /* No options for now.  */
+  if (has_option (line, "--quick"))
+    ctrl->timeout = opt.connect_quick_timeout;
   line = skip_options (line);
 
+  err = ensure_keyserver (ctrl);  /* FIXME: Why do we needs this here?  */
+  if (err)
+    goto leave;
+
   /* Setup an output stream and perform the get.  */
   outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
   if (!outfp)
     err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
   else
     {
+      ctrl->server_local->inhibit_data_logging = 1;
+      ctrl->server_local->inhibit_data_logging_now = 0;
+      ctrl->server_local->inhibit_data_logging_count = 0;
       err = ks_action_fetch (ctrl, line, outfp);
       es_fclose (outfp);
+      ctrl->server_local->inhibit_data_logging = 0;
     }
 
+ leave:
   return leave_cmd (ctx, err);
 }
 
@@ -1904,7 +2653,7 @@ static const char hlp_ks_put[] =
   "  INQUIRE KEYBLOCK_INFO\n"
   "\n"
   "The client shall respond with a colon delimited info lines (the output\n"
-  "of 'for x in keys sigs; do gpg --list-$x --with-colons KEYID; done').\n";
+  "of 'gpg --list-keys --with-colons KEYID').\n";
 static gpg_error_t
 cmd_ks_put (assuan_context_t ctx, char *line)
 {
@@ -1918,6 +2667,10 @@ cmd_ks_put (assuan_context_t ctx, char *line)
   /* No options for now.  */
   line = skip_options (line);
 
+  err = ensure_keyserver (ctrl);
+  if (err)
+    goto leave;
+
   /* Ask for the key material.  */
   err = assuan_inquire (ctx, "KEYBLOCK",
                         &value, &valuelen, MAX_KEYBLOCK_LENGTH);
@@ -1933,8 +2686,7 @@ cmd_ks_put (assuan_context_t ctx, char *line)
       goto leave;
     }
 
-  /* Ask for the key meta data. Not actually needed for HKP servers
-     but we do it anyway to test the client implementaion.  */
+  /* Ask for the key meta data.  */
   err = assuan_inquire (ctx, "KEYBLOCK_INFO",
                         &info, &infolen, MAX_KEYBLOCK_LENGTH);
   if (err)
@@ -1954,6 +2706,130 @@ cmd_ks_put (assuan_context_t ctx, char *line)
 }
 
 
+\f
+static const char hlp_ad_query[] =
+  "AD_QUERY [--first|--next] [--] <filter> \n"
+  "\n"
+  "Query properties from a Windows Active Directory.\n"
+  "Options:\n"
+  "\n"
+  "  --rootdse        - Query the root using serverless binding,\n"
+  "  --subst          - Substitute variables in the filter\n"
+  "  --attr=<attribs> - Comma delimited list of attributes\n"
+  "                     to return.\n"
+  "  --help           - List supported variables\n"
+  "\n"
+  "Extended filter syntax is allowed:\n"
+  "   ^[<base>][&<scope>]&[<filter>]\n"
+  "Usual escaping rules apply.  An ampersand in <base> must\n"
+  "doubled.  <scope> may be \"base\", \"one\", or \"sub\"."
+  ;
+static gpg_error_t
+cmd_ad_query (assuan_context_t ctx, char *line)
+{
+  ctrl_t ctrl = assuan_get_pointer (ctx);
+  gpg_error_t err;
+  unsigned int flags = 0;
+  const char *filter;
+  estream_t outfp = NULL;
+  char *p;
+  char **opt_attr = NULL;
+  const char *s;
+  gnupg_isotime_t opt_newer;
+  int opt_help = 0;
+
+  *opt_newer = 0;
+
+  /* No options for now.  */
+  if (has_option (line, "--first"))
+    flags |= KS_GET_FLAG_FIRST;
+  if (has_option (line, "--next"))
+    flags |= KS_GET_FLAG_NEXT;
+  if (has_option (line, "--rootdse"))
+    flags |= KS_GET_FLAG_ROOTDSE;
+  if (has_option (line, "--subst"))
+    flags |= KS_GET_FLAG_SUBST;
+  if (has_option (line, "--help"))
+    opt_help = 1;
+  if ((s = option_value (line, "--newer"))
+      && !string2isotime (opt_newer, s))
+    {
+      err = set_error (GPG_ERR_SYNTAX, "invalid time format");
+      goto leave;
+    }
+  err = get_option_value (line, "--attr", &p);
+  if (err)
+    goto leave;
+  if (p)
+    {
+      opt_attr = strtokenize (p, ",");
+      if (!opt_attr)
+        {
+          err = gpg_error_from_syserror ();
+          xfree (p);
+          goto leave;
+        }
+      xfree (p);
+    }
+  line = skip_options (line);
+  filter = line;
+
+  if (opt_help)
+    {
+      ks_ldap_help_variables (ctrl);
+      err = 0;
+      goto leave;
+    }
+
+  if ((flags & KS_GET_FLAG_NEXT))
+    {
+      if (*filter || (flags & ~KS_GET_FLAG_NEXT))
+        {
+          err = PARM_ERROR ("No filter or other options allowed with --next");
+          goto leave;
+        }
+    }
+
+  /* Setup an output stream and perform the get.  */
+  outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
+  if (!outfp)
+    {
+      err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
+      goto leave;
+    }
+
+  ctrl->server_local->inhibit_data_logging = 1;
+  ctrl->server_local->inhibit_data_logging_now = 0;
+  ctrl->server_local->inhibit_data_logging_count = 0;
+
+  err = ks_action_query (ctrl,
+                         (flags & KS_GET_FLAG_ROOTDSE)? NULL : "ldap:///",
+                         flags, filter, opt_attr, opt_newer, outfp);
+
+ leave:
+  es_fclose (outfp);
+  xfree (opt_attr);
+  ctrl->server_local->inhibit_data_logging = 0;
+  return leave_cmd (ctx, err);
+}
+
+
+\f
+static const char hlp_loadswdb[] =
+  "LOADSWDB [--force]\n"
+  "\n"
+  "Load and verify the swdb.lst from the Net.";
+static gpg_error_t
+cmd_loadswdb (assuan_context_t ctx, char *line)
+{
+  ctrl_t ctrl = assuan_get_pointer (ctx);
+  gpg_error_t err;
+
+  err = dirmngr_load_swdb (ctrl, has_option (line, "--force"));
+
+  return leave_cmd (ctx, err);
+}
+
 
 \f
 static const char hlp_getinfo[] =
@@ -1962,14 +2838,21 @@ static const char hlp_getinfo[] =
   "Multi purpose command to return certain information.  \n"
   "Supported values of WHAT are:\n"
   "\n"
-  "version     - Return the version of the program.\n"
-  "pid         - Return the process id of the server.\n"
-  "\n"
-  "socket_name - Return the name of the socket.\n";
+  "version     - Return the version of the program\n"
+  "pid         - Return the process id of the server\n"
+  "tor         - Return OK if running in Tor mode\n"
+  "dnsinfo     - Return info about the DNS resolver\n"
+  "socket_name - Return the name of the socket\n"
+  "session_id  - Return the current session_id\n"
+  "workqueue   - Inspect the work queue\n"
+  "stats       - Print stats\n"
+  "getenv NAME - Return value of envvar NAME\n";
 static gpg_error_t
 cmd_getinfo (assuan_context_t ctx, char *line)
 {
+  ctrl_t ctrl = assuan_get_pointer (ctx);
   gpg_error_t err;
+  char numbuf[50];
 
   if (!strcmp (line, "version"))
     {
@@ -1978,26 +2861,110 @@ cmd_getinfo (assuan_context_t ctx, char *line)
     }
   else if (!strcmp (line, "pid"))
     {
-      char numbuf[50];
-
       snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
       err = assuan_send_data (ctx, numbuf, strlen (numbuf));
     }
   else if (!strcmp (line, "socket_name"))
     {
-      const char *s = dirmngr_user_socket_name ();
-
-      if (!s)
-        s = dirmngr_sys_socket_name ();
+      const char *s = dirmngr_get_current_socket_name ();
+      err = assuan_send_data (ctx, s, strlen (s));
+    }
+  else if (!strcmp (line, "session_id"))
+    {
+      snprintf (numbuf, sizeof numbuf, "%u", ctrl->server_local->session_id);
+      err = assuan_send_data (ctx, numbuf, strlen (numbuf));
+    }
+  else if (!strcmp (line, "tor"))
+    {
+      int use_tor;
 
-      if (s)
-        err = assuan_send_data (ctx, s, strlen (s));
+      use_tor = dirmngr_use_tor ();
+      if (use_tor)
+        {
+          if (!is_tor_running (ctrl))
+            err = assuan_write_status (ctx, "NO_TOR", "Tor not running");
+          else
+            err = 0;
+          if (!err)
+            assuan_set_okay_line (ctx, use_tor == 1 ? "- Tor mode is enabled"
+                                  /**/              : "- Tor mode is enforced");
+        }
       else
-        err = gpg_error (GPG_ERR_NO_DATA);
+        err = set_error (GPG_ERR_FALSE, "Tor mode is NOT enabled");
     }
+  else if (!strcmp (line, "dnsinfo"))
+    {
+      if (standard_resolver_p ())
+        assuan_set_okay_line
+          (ctx, "- Forced use of System resolver (w/o Tor support)");
+      else
+        {
+#ifdef USE_LIBDNS
+          assuan_set_okay_line (ctx, (recursive_resolver_p ()
+                                      ? "- Libdns recursive resolver"
+                                      : "- Libdns stub resolver"));
+#else
+          assuan_set_okay_line (ctx, "- System resolver (w/o Tor support)");
+#endif
+        }
+      err = 0;
+    }
+  else if (!strcmp (line, "workqueue"))
+    {
+      workqueue_dump_queue (ctrl);
+      err = 0;
+    }
+  else if (!strcmp (line, "stats"))
+    {
+      cert_cache_print_stats (ctrl);
+      domaininfo_print_stats (ctrl);
+      err = 0;
+    }
+  else if (!strncmp (line, "getenv", 6)
+           && (line[6] == ' ' || line[6] == '\t' || !line[6]))
+    {
+      line += 6;
+      while (*line == ' ' || *line == '\t')
+        line++;
+      if (!*line)
+        err = gpg_error (GPG_ERR_MISSING_VALUE);
+      else
+        {
+          const char *s = getenv (line);
+          if (!s)
+            {
+              err = set_error (GPG_ERR_NOT_FOUND, "No such envvar");
+              goto leave;
+            }
+          err = assuan_send_data (ctx, s, strlen (s));
+        }
+    }
+#ifdef HAVE_W32_SYSTEM
+  else if (!strcmp (line, "sid"))
+    {
+      PSID mysid;
+      char *sidstr;
+
+      mysid = w32_get_user_sid ();
+      if (!mysid)
+        {
+          err = set_error (GPG_ERR_NOT_FOUND, "Error getting my SID");
+          goto leave;
+        }
+
+      if (!ConvertSidToStringSid (mysid, &sidstr))
+        {
+          err = set_error (GPG_ERR_BUG, "Error converting SID to a string");
+          goto leave;
+        }
+      err = assuan_send_data (ctx, sidstr, strlen (sidstr));
+      LocalFree (sidstr);
+    }
+#endif /*HAVE_W32_SYSTEM*/
   else
     err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
 
+ leave:
   return leave_cmd (ctx, err);
 }
 
@@ -2012,28 +2979,12 @@ static gpg_error_t
 cmd_killdirmngr (assuan_context_t ctx, char *line)
 {
   ctrl_t ctrl = assuan_get_pointer (ctx);
-  gpg_error_t err;
 
   (void)line;
 
-  if (opt.system_daemon)
-    {
-      if (opt.system_service)
-        err = set_error (GPG_ERR_NOT_SUPPORTED,
-                         "can't do that whilst running as system service");
-      else
-        err = check_owner_permission (ctx,
-                                      "no permission to kill this process");
-    }
-  else
-    err = 0;
-
-  if (!err)
-    {
-      ctrl->server_local->stopme = 1;
-      err = gpg_error (GPG_ERR_EOF);
-    }
-  return err;
+  ctrl->server_local->stopme = 1;
+  assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
+  return 0;
 }
 
 
@@ -2048,27 +2999,24 @@ cmd_reloaddirmngr (assuan_context_t ctx, char *line)
   (void)ctx;
   (void)line;
 
- if (opt.system_daemon)
-    {
-#ifndef HAVE_W32_SYSTEM
-      {
-        gpg_err_code_t ec;
-        assuan_peercred_t cred;
-
-        ec = gpg_err_code (assuan_get_peercred (ctx, &cred));
-        if (!ec && cred->uid)
-          ec = GPG_ERR_EPERM; /* Only root may terminate.  */
-        if (ec)
-          return set_error (ec, "no permission to reload this process");
-      }
-#endif
-    }
-
   dirmngr_sighup_action ();
   return 0;
 }
 
 
+static const char hlp_flushcrls[] =
+  "FLUSHCRLS\n"
+  "\n"
+  "Remove all cached CRLs from memory and\n"
+  "the file system.";
+static gpg_error_t
+cmd_flushcrls (assuan_context_t ctx, char *line)
+{
+  (void)line;
+
+  return leave_cmd (ctx, crl_cache_flush () ? GPG_ERR_GENERAL : 0);
+}
+
 
 \f
 /* Tell the assuan library about our commands. */
@@ -2081,6 +3029,7 @@ register_commands (assuan_context_t ctx)
     const char * const help;
   } table[] = {
     { "DNS_CERT",   cmd_dns_cert,   hlp_dns_cert },
+    { "WKD_GET",    cmd_wkd_get,    hlp_wkd_get },
     { "LDAPSERVER", cmd_ldapserver, hlp_ldapserver },
     { "ISVALID",    cmd_isvalid,    hlp_isvalid },
     { "CHECKCRL",   cmd_checkcrl,   hlp_checkcrl },
@@ -2095,9 +3044,12 @@ register_commands (assuan_context_t ctx)
     { "KS_GET",     cmd_ks_get,     hlp_ks_get },
     { "KS_FETCH",   cmd_ks_fetch,   hlp_ks_fetch },
     { "KS_PUT",     cmd_ks_put,     hlp_ks_put },
+    { "AD_QUERY",   cmd_ad_query,   hlp_ad_query },
     { "GETINFO",    cmd_getinfo,    hlp_getinfo },
+    { "LOADSWDB",   cmd_loadswdb,   hlp_loadswdb },
     { "KILLDIRMNGR",cmd_killdirmngr,hlp_killdirmngr },
     { "RELOADDIRMNGR",cmd_reloaddirmngr,hlp_reloaddirmngr },
+    { "FLUSHCRLS",  cmd_flushcrls,  hlp_flushcrls },
     { NULL, NULL }
   };
   int i, j, rc;
@@ -2128,10 +3080,35 @@ reset_notify (assuan_context_t ctx, char *line)
 }
 
 
+/* This function is called by our assuan log handler to test whether a
+ * log message shall really be printed.  The function must return
+ * false to inhibit the logging of MSG.  CAT gives the requested log
+ * category.  MSG might be NULL. */
+int
+dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat,
+                            const char *msg)
+{
+  ctrl_t ctrl = assuan_get_pointer (ctx);
+
+  (void)cat;
+  (void)msg;
+
+  if (!ctrl || !ctrl->server_local)
+    return 1; /* Can't decide - allow logging.  */
+
+  if (!ctrl->server_local->inhibit_data_logging)
+    return 1; /* Not requested - allow logging.  */
+
+  /* Disallow logging if *_now is true.  */
+  return !ctrl->server_local->inhibit_data_logging_now;
+}
+
+
 /* Startup the server and run the main command loop.  With FD = -1,
-   use stdin/stdout. */
+ * use stdin/stdout.  SESSION_ID is either 0 or a unique number
+ * identifying a session.  */
 void
-start_command_handler (assuan_fd_t fd)
+start_command_handler (assuan_fd_t fd, unsigned int session_id)
 {
   static const char hello[] = "Dirmngr " VERSION " at your service";
   static char *hello_line;
@@ -2192,22 +3169,13 @@ start_command_handler (assuan_fd_t fd)
 
   if (!hello_line)
     {
-      size_t n;
-      const char *cfgname;
-
-      cfgname = opt.config_filename? opt.config_filename : "[none]";
-
-      n = (30 + strlen (opt.homedir) + strlen (cfgname)
-           + strlen (hello) + 1);
-      hello_line = xmalloc (n+1);
-      snprintf (hello_line, n,
-                "Home: %s\n"
-                "Config: %s\n"
-                "%s",
-                opt.homedir,
-                cfgname,
-                hello);
-      hello_line[n] = 0;
+      hello_line = xtryasprintf
+        ("Home: %s\n"
+         "Config: %s\n"
+         "%s",
+         gnupg_homedir (),
+         opt.config_filename? opt.config_filename : "[none]",
+         hello);
     }
 
   ctrl->server_local->assuan_ctx = ctx;
@@ -2217,6 +3185,8 @@ start_command_handler (assuan_fd_t fd)
   assuan_register_option_handler (ctx, option_handler);
   assuan_register_reset_notify (ctx, reset_notify);
 
+  ctrl->server_local->session_id = session_id;
+
   for (;;)
     {
       rc = assuan_accept (ctx);
@@ -2248,6 +3218,7 @@ start_command_handler (assuan_fd_t fd)
         }
     }
 
+
 #if USE_LDAP
   ldap_wrapper_connection_cleanup (ctrl);
 
@@ -2255,6 +3226,8 @@ start_command_handler (assuan_fd_t fd)
 #endif /*USE_LDAP*/
   ctrl->server_local->ldapservers = NULL;
 
+  release_ctrl_keyservers (ctrl);
+
   ctrl->server_local->assuan_ctx = NULL;
   assuan_release (ctx);
 
@@ -2266,6 +3239,10 @@ start_command_handler (assuan_fd_t fd)
                ctrl->refcount);
   else
     {
+#if USE_LDAP
+      ks_ldap_free_state (ctrl->ks_get_state);
+      ctrl->ks_get_state = NULL;
+#endif
       release_ctrl_ocsp_certs (ctrl);
       xfree (ctrl->server_local);
       dirmngr_deinit_default_ctrl (ctrl);
@@ -2282,30 +3259,13 @@ dirmngr_status (ctrl_t ctrl, const char *keyword, ...)
 {
   gpg_error_t err = 0;
   va_list arg_ptr;
-  const char *text;
+  assuan_context_t ctx;
 
   va_start (arg_ptr, keyword);
 
-  if (ctrl->server_local)
+  if (ctrl->server_local && (ctx = ctrl->server_local->assuan_ctx))
     {
-      assuan_context_t ctx = ctrl->server_local->assuan_ctx;
-      char buf[950], *p;
-      size_t n;
-
-      p = buf;
-      n = 0;
-      while ( (text = va_arg (arg_ptr, const char *)) )
-        {
-          if (n)
-            {
-              *p++ = ' ';
-              n++;
-            }
-          for ( ; *text && n < DIM (buf)-2; n++)
-            *p++ = *text++;
-        }
-      *p = 0;
-      err = assuan_write_status (ctx, keyword, buf);
+      err = vprint_assuan_status_strings (ctx, keyword, arg_ptr);
     }
 
   va_end (arg_ptr);
@@ -2313,16 +3273,15 @@ dirmngr_status (ctrl_t ctrl, const char *keyword, ...)
 }
 
 
-/* Print a help status line.  TEXTLEN gives the length of the text
-   from TEXT to be printed.  The function splits text at LFs.  */
+/* Print a help status line.  The function splits text at LFs.  */
 gpg_error_t
 dirmngr_status_help (ctrl_t ctrl, const char *text)
 {
   gpg_error_t err = 0;
+  assuan_context_t ctx;
 
-  if (ctrl->server_local)
+  if (ctrl->server_local && (ctx = ctrl->server_local->assuan_ctx))
     {
-      assuan_context_t ctx = ctrl->server_local->assuan_ctx;
       char buf[950], *p;
       size_t n;
 
@@ -2343,6 +3302,56 @@ dirmngr_status_help (ctrl_t ctrl, const char *text)
   return err;
 }
 
+
+/* Print a help status line using a printf like format.  The function
+ * splits text at LFs.  With CTRL beeing NULL, the function behaves
+ * like log_info.  */
+gpg_error_t
+dirmngr_status_helpf (ctrl_t ctrl, const char *format, ...)
+{
+  va_list arg_ptr;
+  gpg_error_t err;
+  char *buf;
+
+  va_start (arg_ptr, format);
+  if (ctrl)
+    {
+      buf = es_vbsprintf (format, arg_ptr);
+      err = buf? 0 : gpg_error_from_syserror ();
+      if (!err)
+        err = dirmngr_status_help (ctrl, buf);
+      es_free (buf);
+    }
+  else
+    {
+      log_logv (GPGRT_LOGLVL_INFO, format, arg_ptr);
+      err = 0;
+    }
+  va_end (arg_ptr);
+  return err;
+}
+
+
+/* This function is similar to print_assuan_status but takes a CTRL
+ * arg instead of an assuan context as first argument.  */
+gpg_error_t
+dirmngr_status_printf (ctrl_t ctrl, const char *keyword,
+                       const char *format, ...)
+{
+  gpg_error_t err;
+  va_list arg_ptr;
+  assuan_context_t ctx;
+
+  if (!ctrl || !ctrl->server_local || !(ctx = ctrl->server_local->assuan_ctx))
+    return 0;
+
+  va_start (arg_ptr, format);
+  err = vprint_assuan_status (ctx, keyword, format, arg_ptr);
+  va_end (arg_ptr);
+  return err;
+}
+
+
 /* Send a tick progress indicator back.  Fixme: This is only done for
    the currently active channel.  */
 gpg_error_t