"Fossies" - the Fresh Open Source Software Archive

Member "gnupg-2.2.17/g10/keyserver.c" (9 Jul 2019, 59052 Bytes) of package /linux/misc/gnupg-2.2.17.tar.bz2:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "keyserver.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.2.16_vs_2.2.17.

    1 /* keyserver.c - generic keyserver code
    2  * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
    3  *               2009, 2011, 2012 Free Software Foundation, Inc.
    4  * Copyright (C) 2014 Werner Koch
    5  *
    6  * This file is part of GnuPG.
    7  *
    8  * GnuPG is free software; you can redistribute it and/or modify
    9  * it under the terms of the GNU General Public License as published by
   10  * the Free Software Foundation; either version 3 of the License, or
   11  * (at your option) any later version.
   12  *
   13  * GnuPG is distributed in the hope that it will be useful,
   14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16  * GNU General Public License for more details.
   17  *
   18  * You should have received a copy of the GNU General Public License
   19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
   20  */
   21 
   22 #include <config.h>
   23 #include <ctype.h>
   24 #include <stdio.h>
   25 #include <string.h>
   26 #include <stdlib.h>
   27 #include <errno.h>
   28 
   29 #include "gpg.h"
   30 #include "../common/iobuf.h"
   31 #include "filter.h"
   32 #include "keydb.h"
   33 #include "../common/status.h"
   34 #include "exec.h"
   35 #include "main.h"
   36 #include "../common/i18n.h"
   37 #include "../common/ttyio.h"
   38 #include "options.h"
   39 #include "packet.h"
   40 #include "trustdb.h"
   41 #include "keyserver-internal.h"
   42 #include "../common/util.h"
   43 #include "../common/membuf.h"
   44 #include "../common/mbox-util.h"
   45 #include "call-dirmngr.h"
   46 
   47 #ifdef HAVE_W32_SYSTEM
   48 /* It seems Vista doesn't grok X_OK and so fails access() tests.
   49    Previous versions interpreted X_OK as F_OK anyway, so we'll just
   50    use F_OK directly. */
   51 #undef X_OK
   52 #define X_OK F_OK
   53 #endif /* HAVE_W32_SYSTEM */
   54 
   55 struct keyrec
   56 {
   57   KEYDB_SEARCH_DESC desc;
   58   u32 createtime,expiretime;
   59   int size,flags;
   60   byte type;
   61   IOBUF uidbuf;
   62   unsigned int lines;
   63 };
   64 
   65 /* Parameters for the search line handler.  */
   66 struct search_line_handler_parm_s
   67 {
   68   ctrl_t ctrl;     /* The session control structure.  */
   69   char *searchstr_disp;  /* Native encoded search string or NULL.  */
   70   KEYDB_SEARCH_DESC *desc; /* Array with search descriptions.  */
   71   int count;      /* Number of keys we are currently prepared to
   72                      handle.  This is the size of the DESC array.  If
   73                      it is too small, it will grow safely.  */
   74   int validcount; /* Enable the "Key x-y of z" messages. */
   75   int nkeys;      /* Number of processed records.  */
   76   int any_lines;  /* At least one line has been processed.  */
   77   unsigned int numlines;  /* Counter for displayed lines.  */
   78   int eof_seen;   /* EOF encountered.  */
   79   int not_found;  /* Set if no keys have been found.  */
   80 };
   81 
   82 
   83 enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH};
   84 
   85 static struct parse_options keyserver_opts[]=
   86   {
   87     /* some of these options are not real - just for the help
   88        message */
   89     {"max-cert-size",0,NULL,NULL},  /* MUST be the first in this array! */
   90     {"http-proxy", KEYSERVER_HTTP_PROXY, NULL, /* MUST be the second!  */
   91      N_("override proxy options set for dirmngr")},
   92 
   93     {"include-revoked",0,NULL,N_("include revoked keys in search results")},
   94     {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")},
   95     {"timeout", KEYSERVER_TIMEOUT, NULL,
   96      N_("override timeout options set for dirmngr")},
   97     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL,
   98      NULL},
   99     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL,
  100      N_("automatically retrieve keys when verifying signatures")},
  101     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL,
  102      N_("honor the preferred keyserver URL set on the key")},
  103     {"honor-pka-record",KEYSERVER_HONOR_PKA_RECORD,NULL,
  104      N_("honor the PKA record set on a key when retrieving keys")},
  105     {NULL,0,NULL,NULL}
  106   };
  107 
  108 static gpg_error_t keyserver_get (ctrl_t ctrl,
  109                                   KEYDB_SEARCH_DESC *desc, int ndesc,
  110                                   struct keyserver_spec *override_keyserver,
  111                                   int quick,
  112                                   unsigned char **r_fpr, size_t *r_fprlen);
  113 static gpg_error_t keyserver_put (ctrl_t ctrl, strlist_t keyspecs);
  114 
  115 
  116 /* Reasonable guess.  The commonly used test key simon.josefsson.org
  117    is larger than 32k, thus we need at least this value. */
  118 #define DEFAULT_MAX_CERT_SIZE 65536
  119 
  120 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE;
  121 
  122 
  123 static void
  124 warn_kshelper_option(char *option, int noisy)
  125 {
  126   char *p;
  127 
  128   if ((p=strchr (option, '=')))
  129     *p = 0;
  130 
  131   if (!strcmp (option, "ca-cert-file"))
  132     log_info ("keyserver option '%s' is obsolete; please use "
  133               "'%s' in dirmngr.conf\n",
  134               "ca-cert-file", "hkp-cacert");
  135   else if (!strcmp (option, "check-cert")
  136            || !strcmp (option, "broken-http-proxy"))
  137     log_info ("keyserver option '%s' is obsolete\n", option);
  138   else if (noisy || opt.verbose)
  139     log_info ("keyserver option '%s' is unknown\n", option);
  140 }
  141 
  142 
  143 /* Called from main to parse the args for --keyserver-options.  */
  144 int
  145 parse_keyserver_options(char *options)
  146 {
  147   int ret=1;
  148   char *tok;
  149   char *max_cert=NULL;
  150 
  151   keyserver_opts[0].value=&max_cert;
  152   keyserver_opts[1].value=&opt.keyserver_options.http_proxy;
  153 
  154   while((tok=optsep(&options)))
  155     {
  156       if(tok[0]=='\0')
  157     continue;
  158 
  159       /* We accept quite a few possible options here - some options to
  160      handle specially, the keyserver_options list, and import and
  161      export options that pertain to keyserver operations.  */
  162 
  163       if (!parse_options (tok,&opt.keyserver_options.options, keyserver_opts,0)
  164           && !parse_import_options(tok,&opt.keyserver_options.import_options,0)
  165           && !parse_export_options(tok,&opt.keyserver_options.export_options,0))
  166     {
  167       /* All of the standard options have failed, so the option was
  168          destined for a keyserver plugin as used by GnuPG < 2.1 */
  169       warn_kshelper_option (tok, 1);
  170     }
  171     }
  172 
  173   if(max_cert)
  174     {
  175       max_cert_size=strtoul(max_cert,(char **)NULL,10);
  176 
  177       if(max_cert_size==0)
  178     max_cert_size=DEFAULT_MAX_CERT_SIZE;
  179     }
  180 
  181   return ret;
  182 }
  183 
  184 
  185 void
  186 free_keyserver_spec(struct keyserver_spec *keyserver)
  187 {
  188   xfree(keyserver->uri);
  189   xfree(keyserver->scheme);
  190   xfree(keyserver->auth);
  191   xfree(keyserver->host);
  192   xfree(keyserver->port);
  193   xfree(keyserver->path);
  194   xfree(keyserver->opaque);
  195   free_strlist(keyserver->options);
  196   xfree(keyserver);
  197 }
  198 
  199 /* Return 0 for match */
  200 static int
  201 cmp_keyserver_spec(struct keyserver_spec *one,struct keyserver_spec *two)
  202 {
  203   if(ascii_strcasecmp(one->scheme,two->scheme)==0)
  204     {
  205       if(one->host && two->host && ascii_strcasecmp(one->host,two->host)==0)
  206     {
  207       if((one->port && two->port
  208           && ascii_strcasecmp(one->port,two->port)==0)
  209          || (!one->port && !two->port))
  210         return 0;
  211     }
  212       else if(one->opaque && two->opaque
  213           && ascii_strcasecmp(one->opaque,two->opaque)==0)
  214     return 0;
  215     }
  216 
  217   return 1;
  218 }
  219 
  220 /* Try and match one of our keyservers.  If we can, return that.  If
  221    we can't, return our input. */
  222 struct keyserver_spec *
  223 keyserver_match(struct keyserver_spec *spec)
  224 {
  225   struct keyserver_spec *ks;
  226 
  227   for(ks=opt.keyserver;ks;ks=ks->next)
  228     if(cmp_keyserver_spec(spec,ks)==0)
  229       return ks;
  230 
  231   return spec;
  232 }
  233 
  234 /* TODO: once we cut over to an all-curl world, we don't need this
  235    parser any longer so it can be removed, or at least moved to
  236    keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */
  237 
  238 keyserver_spec_t
  239 parse_keyserver_uri (const char *string,int require_scheme)
  240 {
  241   int assume_hkp=0;
  242   struct keyserver_spec *keyserver;
  243   const char *idx;
  244   int count;
  245   char *uri, *duped_uri, *options;
  246 
  247   log_assert (string);
  248 
  249   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
  250 
  251   duped_uri = uri = xstrdup (string);
  252 
  253   options=strchr(uri,' ');
  254   if(options)
  255     {
  256       char *tok;
  257 
  258       *options='\0';
  259       options++;
  260 
  261       while((tok=optsep(&options)))
  262     warn_kshelper_option (tok, 0);
  263     }
  264 
  265   /* Get the scheme */
  266 
  267   for(idx=uri,count=0;*idx && *idx!=':';idx++)
  268     {
  269       count++;
  270 
  271       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
  272      there clearly isn't a scheme so get out early. */
  273       if(*idx=='[')
  274     {
  275       /* Was the '[' the first thing in the string?  If not, we
  276          have a mangled scheme with a [ in it so fail. */
  277       if(count==1)
  278         break;
  279       else
  280         goto fail;
  281     }
  282     }
  283 
  284   if(count==0)
  285     goto fail;
  286 
  287   if(*idx=='\0' || *idx=='[')
  288     {
  289       if(require_scheme)
  290     return NULL;
  291 
  292       /* Assume HKP if there is no scheme */
  293       assume_hkp=1;
  294       keyserver->scheme=xstrdup("hkp");
  295 
  296       keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1);
  297       strcpy(keyserver->uri,keyserver->scheme);
  298       strcat(keyserver->uri,"://");
  299       strcat(keyserver->uri,uri);
  300     }
  301   else
  302     {
  303       int i;
  304 
  305       keyserver->uri=xstrdup(uri);
  306 
  307       keyserver->scheme=xmalloc(count+1);
  308 
  309       /* Force to lowercase */
  310       for(i=0;i<count;i++)
  311     keyserver->scheme[i]=ascii_tolower(uri[i]);
  312 
  313       keyserver->scheme[i]='\0';
  314 
  315       /* Skip past the scheme and colon */
  316       uri+=count+1;
  317     }
  318 
  319   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
  320     {
  321       log_info ("keyserver option '%s' is obsolete\n",
  322                 "x-broken-hkp");
  323     }
  324   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
  325     {
  326       /* Canonicalize this to "hkp" so it works with both the internal
  327      and external keyserver interface. */
  328       xfree(keyserver->scheme);
  329       keyserver->scheme=xstrdup("hkp");
  330     }
  331 
  332   if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/')
  333     {
  334       /* Three slashes means network path with a default host name.
  335          This is a hack because it does not crok all possible
  336          combinations.  We should better replace all code by the parser
  337          from http.c.  */
  338       keyserver->path = xstrdup (uri+2);
  339     }
  340   else if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
  341     {
  342       /* Two slashes means network path. */
  343 
  344       /* Skip over the "//", if any */
  345       if(!assume_hkp)
  346     uri+=2;
  347 
  348       /* Do we have userinfo auth data present? */
  349       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
  350     count++;
  351 
  352       /* We found a @ before the slash, so that means everything
  353      before the @ is auth data. */
  354       if(*idx=='@')
  355     {
  356       if(count==0)
  357         goto fail;
  358 
  359       keyserver->auth=xmalloc(count+1);
  360       strncpy(keyserver->auth,uri,count);
  361       keyserver->auth[count]='\0';
  362       uri+=count+1;
  363     }
  364 
  365       /* Is it an RFC-2732 ipv6 [literal address] ? */
  366       if(*uri=='[')
  367     {
  368       for(idx=uri+1,count=1;*idx
  369         && ((isascii (*idx) && isxdigit(*idx))
  370                     || *idx==':' || *idx=='.');idx++)
  371         count++;
  372 
  373       /* Is the ipv6 literal address terminated? */
  374       if(*idx==']')
  375         count++;
  376       else
  377         goto fail;
  378     }
  379       else
  380     for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
  381       count++;
  382 
  383       if(count==0)
  384     goto fail;
  385 
  386       keyserver->host=xmalloc(count+1);
  387       strncpy(keyserver->host,uri,count);
  388       keyserver->host[count]='\0';
  389 
  390       /* Skip past the host */
  391       uri+=count;
  392 
  393       if(*uri==':')
  394     {
  395       /* It would seem to be reasonable to limit the range of the
  396          ports to values between 1-65535, but RFC 1738 and 1808
  397          imply there is no limit.  Of course, the real world has
  398          limits. */
  399 
  400       for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
  401         {
  402           count++;
  403 
  404           /* Ports are digits only */
  405           if(!digitp(idx))
  406         goto fail;
  407         }
  408 
  409       keyserver->port=xmalloc(count+1);
  410       strncpy(keyserver->port,uri+1,count);
  411       keyserver->port[count]='\0';
  412 
  413       /* Skip past the colon and port number */
  414       uri+=1+count;
  415     }
  416 
  417       /* Everything else is the path */
  418       if(*uri)
  419     keyserver->path=xstrdup(uri);
  420       else
  421     keyserver->path=xstrdup("/");
  422 
  423       if(keyserver->path[1])
  424     keyserver->flags.direct_uri=1;
  425     }
  426   else if(uri[0]!='/')
  427     {
  428       /* No slash means opaque.  Just record the opaque blob and get
  429      out. */
  430       keyserver->opaque=xstrdup(uri);
  431     }
  432   else
  433     {
  434       /* One slash means absolute path.  We don't need to support that
  435      yet. */
  436       goto fail;
  437     }
  438 
  439   xfree (duped_uri);
  440   return keyserver;
  441 
  442  fail:
  443   free_keyserver_spec(keyserver);
  444 
  445   xfree (duped_uri);
  446   return NULL;
  447 }
  448 
  449 struct keyserver_spec *
  450 parse_preferred_keyserver(PKT_signature *sig)
  451 {
  452   struct keyserver_spec *spec=NULL;
  453   const byte *p;
  454   size_t plen;
  455 
  456   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
  457   if(p && plen)
  458     {
  459       byte *dupe=xmalloc(plen+1);
  460 
  461       memcpy(dupe,p,plen);
  462       dupe[plen]='\0';
  463       spec = parse_keyserver_uri (dupe, 1);
  464       xfree(dupe);
  465     }
  466 
  467   return spec;
  468 }
  469 
  470 static void
  471 print_keyrec (ctrl_t ctrl, int number,struct keyrec *keyrec)
  472 {
  473   int i;
  474 
  475   iobuf_writebyte(keyrec->uidbuf,0);
  476   iobuf_flush_temp(keyrec->uidbuf);
  477   es_printf ("(%d)\t%s  ", number, iobuf_get_temp_buffer (keyrec->uidbuf));
  478 
  479   if (keyrec->size>0)
  480     es_printf ("%d bit ", keyrec->size);
  481 
  482   if(keyrec->type)
  483     {
  484       const char *str;
  485 
  486       str = openpgp_pk_algo_name (keyrec->type);
  487 
  488       if (str && strcmp (str, "?"))
  489     es_printf ("%s ",str);
  490       else
  491     es_printf ("unknown ");
  492     }
  493 
  494   switch(keyrec->desc.mode)
  495     {
  496       /* If the keyserver helper gave us a short keyid, we have no
  497      choice but to use it.  Do check --keyid-format to add a 0x if
  498      needed. */
  499     case KEYDB_SEARCH_MODE_SHORT_KID:
  500       es_printf ("key %s%08lX",
  501                  (opt.keyid_format==KF_0xSHORT
  502                   || opt.keyid_format==KF_0xLONG)?"0x":"",
  503                  (ulong)keyrec->desc.u.kid[1]);
  504       break;
  505 
  506       /* However, if it gave us a long keyid, we can honor
  507      --keyid-format via keystr(). */
  508     case KEYDB_SEARCH_MODE_LONG_KID:
  509       es_printf ("key %s",keystr(keyrec->desc.u.kid));
  510       break;
  511 
  512       /* If it gave us a PGP 2.x fingerprint, not much we can do
  513      beyond displaying it. */
  514     case KEYDB_SEARCH_MODE_FPR16:
  515       es_printf ("key ");
  516       for(i=0;i<16;i++)
  517     es_printf ("%02X",keyrec->desc.u.fpr[i]);
  518       break;
  519 
  520       /* If we get a modern fingerprint, we have the most
  521      flexibility. */
  522     case KEYDB_SEARCH_MODE_FPR20:
  523       {
  524     u32 kid[2];
  525     keyid_from_fingerprint (ctrl, keyrec->desc.u.fpr,20,kid);
  526     es_printf("key %s",keystr(kid));
  527       }
  528       break;
  529 
  530     default:
  531       BUG();
  532       break;
  533     }
  534 
  535   if(keyrec->createtime>0)
  536     {
  537       es_printf (", ");
  538       es_printf (_("created: %s"), strtimestamp(keyrec->createtime));
  539     }
  540 
  541   if(keyrec->expiretime>0)
  542     {
  543       es_printf (", ");
  544       es_printf (_("expires: %s"), strtimestamp(keyrec->expiretime));
  545     }
  546 
  547   if (keyrec->flags&1)
  548     es_printf (" (%s)", _("revoked"));
  549   if(keyrec->flags&2)
  550     es_printf (" (%s)", _("disabled"));
  551   if(keyrec->flags&4)
  552     es_printf (" (%s)", _("expired"));
  553 
  554   es_printf ("\n");
  555 }
  556 
  557 /* Returns a keyrec (which must be freed) once a key is complete, and
  558    NULL otherwise.  Call with a NULL keystring once key parsing is
  559    complete to return any unfinished keys. */
  560 static struct keyrec *
  561 parse_keyrec(char *keystring)
  562 {
  563   /* FIXME: Remove the static and put the data into the parms we use
  564      for the caller anyway.  */
  565   static struct keyrec *work=NULL;
  566   struct keyrec *ret=NULL;
  567   char *record;
  568   int i;
  569 
  570   if(keystring==NULL)
  571     {
  572       if(work==NULL)
  573     return NULL;
  574       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
  575     {
  576       xfree(work);
  577       return NULL;
  578     }
  579       else
  580     {
  581       ret=work;
  582       work=NULL;
  583       return ret;
  584     }
  585     }
  586 
  587   if(work==NULL)
  588     {
  589       work=xmalloc_clear(sizeof(struct keyrec));
  590       work->uidbuf=iobuf_temp();
  591     }
  592 
  593   trim_trailing_ws (keystring, strlen (keystring));
  594 
  595   if((record=strsep(&keystring,":"))==NULL)
  596     return ret;
  597 
  598   if(ascii_strcasecmp("pub",record)==0)
  599     {
  600       char *tok;
  601       gpg_error_t err;
  602 
  603       if(work->desc.mode)
  604     {
  605       ret=work;
  606       work=xmalloc_clear(sizeof(struct keyrec));
  607       work->uidbuf=iobuf_temp();
  608     }
  609 
  610       if((tok=strsep(&keystring,":"))==NULL)
  611     return ret;
  612 
  613       err = classify_user_id (tok, &work->desc, 1);
  614       if (err || (work->desc.mode    != KEYDB_SEARCH_MODE_SHORT_KID
  615                   && work->desc.mode != KEYDB_SEARCH_MODE_LONG_KID
  616                   && work->desc.mode != KEYDB_SEARCH_MODE_FPR16
  617                   && work->desc.mode != KEYDB_SEARCH_MODE_FPR20))
  618     {
  619       work->desc.mode=KEYDB_SEARCH_MODE_NONE;
  620       return ret;
  621     }
  622 
  623       /* Note all items after this are optional.  This allows us to
  624          have a pub line as simple as pub:keyid and nothing else. */
  625 
  626       work->lines++;
  627 
  628       if((tok=strsep(&keystring,":"))==NULL)
  629     return ret;
  630 
  631       work->type=atoi(tok);
  632 
  633       if((tok=strsep(&keystring,":"))==NULL)
  634     return ret;
  635 
  636       work->size=atoi(tok);
  637 
  638       if((tok=strsep(&keystring,":"))==NULL)
  639     return ret;
  640 
  641       if(atoi(tok)<=0)
  642     work->createtime=0;
  643       else
  644     work->createtime=atoi(tok);
  645 
  646       if((tok=strsep(&keystring,":"))==NULL)
  647     return ret;
  648 
  649       if(atoi(tok)<=0)
  650     work->expiretime=0;
  651       else
  652     {
  653       work->expiretime=atoi(tok);
  654       /* Force the 'e' flag on if this key is expired. */
  655       if(work->expiretime<=make_timestamp())
  656         work->flags|=4;
  657     }
  658 
  659       if((tok=strsep(&keystring,":"))==NULL)
  660     return ret;
  661 
  662       while(*tok)
  663     switch(*tok++)
  664       {
  665       case 'r':
  666       case 'R':
  667         work->flags|=1;
  668         break;
  669 
  670       case 'd':
  671       case 'D':
  672         work->flags|=2;
  673         break;
  674 
  675       case 'e':
  676       case 'E':
  677         work->flags|=4;
  678         break;
  679       }
  680     }
  681   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
  682     {
  683       char *userid,*tok,*decoded;
  684 
  685       if((tok=strsep(&keystring,":"))==NULL)
  686     return ret;
  687 
  688       if(strlen(tok)==0)
  689     return ret;
  690 
  691       userid=tok;
  692 
  693       /* By definition, de-%-encoding is always smaller than the
  694          original string so we can decode in place. */
  695 
  696       i=0;
  697 
  698       while(*tok)
  699     if(tok[0]=='%' && tok[1] && tok[2])
  700       {
  701             int c;
  702 
  703         userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
  704         i++;
  705         tok+=3;
  706       }
  707     else
  708       userid[i++]=*tok++;
  709 
  710       /* We don't care about the other info provided in the uid: line
  711          since no keyserver supports marking userids with timestamps
  712          or revoked/expired/disabled yet. */
  713 
  714       /* No need to check for control characters, as utf8_to_native
  715      does this for us. */
  716 
  717       decoded=utf8_to_native(userid,i,0);
  718       if(strlen(decoded)>opt.screen_columns-10)
  719     decoded[opt.screen_columns-10]='\0';
  720       iobuf_writestr(work->uidbuf,decoded);
  721       xfree(decoded);
  722       iobuf_writestr(work->uidbuf,"\n\t");
  723       work->lines++;
  724     }
  725 
  726   /* Ignore any records other than "pri" and "uid" for easy future
  727      growth. */
  728 
  729   return ret;
  730 }
  731 
  732 /* Show a prompt and allow the user to select keys for retrieval.  */
  733 static gpg_error_t
  734 show_prompt (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int numdesc,
  735              int count, const char *search)
  736 {
  737   gpg_error_t err;
  738   char *answer = NULL;
  739 
  740   es_fflush (es_stdout);
  741 
  742   if (count && opt.command_fd == -1)
  743     {
  744       static int from = 1;
  745       tty_printf ("Keys %d-%d of %d for \"%s\".  ",
  746                   from, numdesc, count, search);
  747       from = numdesc + 1;
  748     }
  749 
  750  again:
  751   err = 0;
  752   xfree (answer);
  753   answer = cpr_get_no_help ("keysearch.prompt",
  754                             _("Enter number(s), N)ext, or Q)uit > "));
  755   /* control-d */
  756   if (answer[0]=='\x04')
  757     {
  758       tty_printf ("Q\n");
  759       answer[0] = 'q';
  760     }
  761 
  762   if (answer[0]=='q' || answer[0]=='Q')
  763     err = gpg_error (GPG_ERR_CANCELED);
  764   else if (atoi (answer) >= 1 && atoi (answer) <= numdesc)
  765     {
  766       char *split = answer;
  767       char *num;
  768       int numarray[50];
  769       int numidx = 0;
  770       int idx;
  771 
  772       while ((num = strsep (&split, " ,")))
  773     if (atoi (num) >= 1 && atoi (num) <= numdesc)
  774           {
  775             if (numidx >= DIM (numarray))
  776               {
  777                 tty_printf ("Too many keys selected\n");
  778                 goto again;
  779               }
  780             numarray[numidx++] = atoi (num);
  781           }
  782 
  783       if (!numidx)
  784         goto again;
  785 
  786       {
  787         KEYDB_SEARCH_DESC *selarray;
  788 
  789         selarray = xtrymalloc (numidx * sizeof *selarray);
  790         if (!selarray)
  791           {
  792             err = gpg_error_from_syserror ();
  793             goto leave;
  794           }
  795         for (idx = 0; idx < numidx; idx++)
  796           selarray[idx] = desc[numarray[idx]-1];
  797         err = keyserver_get (ctrl, selarray, numidx, NULL, 0, NULL, NULL);
  798         xfree (selarray);
  799       }
  800     }
  801 
  802  leave:
  803   xfree (answer);
  804   return err;
  805 }
  806 
  807 
  808 /* This is a callback used by call-dirmngr.c to process the result of
  809    KS_SEARCH command.  If SPECIAL is 0, LINE is the actual data line
  810    received with all escaping removed and guaranteed to be exactly one
  811    line with stripped LF; an EOF is indicated by LINE passed as NULL.
  812    If special is 1, the line contains the source of the information
  813    (usually an URL).  LINE may be modified after return.  */
  814 static gpg_error_t
  815 search_line_handler (void *opaque, int special, char *line)
  816 {
  817   struct search_line_handler_parm_s *parm = opaque;
  818   gpg_error_t err = 0;
  819   struct keyrec *keyrec;
  820 
  821   if (special == 1)
  822     {
  823       log_info ("data source: %s\n", line);
  824       return 0;
  825     }
  826   else if (special)
  827     {
  828       log_debug ("unknown value %d for special search callback", special);
  829       return 0;
  830     }
  831 
  832   if (parm->eof_seen && line)
  833     {
  834       log_debug ("ooops: unexpected data after EOF\n");
  835       line = NULL;
  836     }
  837 
  838   /* Print the received line.  */
  839   if (opt.with_colons && line)
  840     {
  841       es_printf ("%s\n", line);
  842     }
  843 
  844   /* Look for an info: line.  The only current info: values defined
  845      are the version and key count. */
  846   if (line && !parm->any_lines && !ascii_strncasecmp ("info:", line, 5))
  847     {
  848       char *str = line + 5;
  849       char *tok;
  850 
  851       if ((tok = strsep (&str, ":")))
  852         {
  853           int version;
  854 
  855           if (sscanf (tok, "%d", &version) !=1 )
  856             version = 1;
  857 
  858           if (version !=1 )
  859             {
  860               log_error (_("invalid keyserver protocol "
  861                            "(us %d!=handler %d)\n"), 1, version);
  862               return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
  863             }
  864         }
  865 
  866       if ((tok = strsep (&str, ":"))
  867           && sscanf (tok, "%d", &parm->count) == 1)
  868         {
  869           if (!parm->count)
  870             parm->not_found = 1;/* Server indicated that no items follow.  */
  871           else if (parm->count < 0)
  872             parm->count = 10;   /* Bad value - assume something reasonable.  */
  873           else
  874             parm->validcount = 1; /* COUNT seems to be okay.  */
  875         }
  876 
  877       parm->any_lines = 1;
  878       return 0; /* Line processing finished.  */
  879     }
  880 
  881  again:
  882   if (line)
  883     keyrec = parse_keyrec (line);
  884   else
  885     {
  886       /* Received EOF - flush data */
  887       parm->eof_seen = 1;
  888       keyrec = parse_keyrec (NULL);
  889       if (!keyrec)
  890         {
  891           if (!parm->nkeys)
  892             parm->not_found = 1;  /* No keys at all.  */
  893           else
  894             {
  895               if (parm->nkeys != parm->count)
  896                 parm->validcount = 0;
  897 
  898               if (!(opt.with_colons && opt.batch))
  899                 {
  900                   err = show_prompt (parm->ctrl, parm->desc, parm->nkeys,
  901                                      parm->validcount? parm->count : 0,
  902                                      parm->searchstr_disp);
  903                   return err;
  904                 }
  905             }
  906         }
  907     }
  908 
  909   /* Save the key in the key array.  */
  910   if (keyrec)
  911     {
  912       /* Allocate or enlarge the key array if needed.  */
  913       if (!parm->desc)
  914         {
  915           if (parm->count < 1)
  916             {
  917               parm->count = 10;
  918               parm->validcount = 0;
  919             }
  920           parm->desc = xtrymalloc (parm->count * sizeof *parm->desc);
  921           if (!parm->desc)
  922             {
  923               err = gpg_error_from_syserror ();
  924               iobuf_close (keyrec->uidbuf);
  925               xfree (keyrec);
  926               return err;
  927             }
  928         }
  929       else if (parm->nkeys == parm->count)
  930         {
  931           /* Keyserver sent more keys than claimed in the info: line. */
  932           KEYDB_SEARCH_DESC *tmp;
  933           int newcount = parm->count + 10;
  934 
  935           tmp = xtryrealloc (parm->desc, newcount * sizeof *parm->desc);
  936           if (!tmp)
  937             {
  938               err = gpg_error_from_syserror ();
  939               iobuf_close (keyrec->uidbuf);
  940               xfree (keyrec);
  941               return err;
  942             }
  943           parm->count = newcount;
  944           parm->desc = tmp;
  945           parm->validcount = 0;
  946         }
  947 
  948       parm->desc[parm->nkeys] = keyrec->desc;
  949 
  950       if (!opt.with_colons)
  951         {
  952           /* SCREEN_LINES - 1 for the prompt. */
  953           if (parm->numlines + keyrec->lines > opt.screen_lines - 1)
  954             {
  955               err = show_prompt (parm->ctrl, parm->desc, parm->nkeys,
  956                                  parm->validcount ? parm->count:0,
  957                                  parm->searchstr_disp);
  958               if (err)
  959                 return err;
  960               parm->numlines = 0;
  961             }
  962 
  963           print_keyrec (parm->ctrl, parm->nkeys+1, keyrec);
  964         }
  965 
  966       parm->numlines += keyrec->lines;
  967       iobuf_close (keyrec->uidbuf);
  968       xfree (keyrec);
  969 
  970       parm->any_lines = 1;
  971       parm->nkeys++;
  972 
  973       /* If we are here due to a flush after the EOF, run again for
  974          the last prompt.  Fixme: Make this code better readable. */
  975       if (parm->eof_seen)
  976         goto again;
  977     }
  978 
  979   return 0;
  980 }
  981 
  982 
  983 
  984 int
  985 keyserver_export (ctrl_t ctrl, strlist_t users)
  986 {
  987   gpg_error_t err;
  988   strlist_t sl=NULL;
  989   KEYDB_SEARCH_DESC desc;
  990   int rc=0;
  991 
  992   /* Weed out descriptors that we don't support sending */
  993   for(;users;users=users->next)
  994     {
  995       err = classify_user_id (users->d, &desc, 1);
  996       if (err || (desc.mode    != KEYDB_SEARCH_MODE_SHORT_KID
  997                   && desc.mode != KEYDB_SEARCH_MODE_LONG_KID
  998                   && desc.mode != KEYDB_SEARCH_MODE_FPR16
  999                   && desc.mode != KEYDB_SEARCH_MODE_FPR20))
 1000     {
 1001       log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
 1002       continue;
 1003     }
 1004       else
 1005     append_to_strlist(&sl,users->d);
 1006     }
 1007 
 1008   if(sl)
 1009     {
 1010       rc = keyserver_put (ctrl, sl);
 1011       free_strlist(sl);
 1012     }
 1013 
 1014   return rc;
 1015 }
 1016 
 1017 
 1018 /* Structure to convey the arg to keyserver_retrieval_screener.  */
 1019 struct ks_retrieval_screener_arg_s
 1020 {
 1021   KEYDB_SEARCH_DESC *desc;
 1022   int ndesc;
 1023 };
 1024 
 1025 
 1026 /* Check whether a key matches the search description.  The function
 1027    returns 0 if the key shall be imported.  */
 1028 static gpg_error_t
 1029 keyserver_retrieval_screener (kbnode_t keyblock, void *opaque)
 1030 {
 1031   struct ks_retrieval_screener_arg_s *arg = opaque;
 1032   KEYDB_SEARCH_DESC *desc = arg->desc;
 1033   int ndesc = arg->ndesc;
 1034   kbnode_t node;
 1035   PKT_public_key *pk;
 1036   int n;
 1037   u32 keyid[2];
 1038   byte fpr[MAX_FINGERPRINT_LEN];
 1039   size_t fpr_len = 0;
 1040 
 1041   /* Secret keys are not expected from a keyserver.  We do not
 1042      care about secret subkeys because the import code takes care
 1043      of skipping them.  Not allowing an import of a public key
 1044      with a secret subkey would make it too easy to inhibit the
 1045      downloading of a public key.  Recall that keyservers do only
 1046      limited checks.  */
 1047   node = find_kbnode (keyblock, PKT_SECRET_KEY);
 1048   if (node)
 1049     return gpg_error (GPG_ERR_GENERAL);   /* Do not import. */
 1050 
 1051   if (!ndesc)
 1052     return 0; /* Okay if no description given.  */
 1053 
 1054   /* Loop over all key packets.  */
 1055   for (node = keyblock; node; node = node->next)
 1056     {
 1057       if (node->pkt->pkttype != PKT_PUBLIC_KEY
 1058           && node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
 1059         continue;
 1060 
 1061       pk = node->pkt->pkt.public_key;
 1062       fingerprint_from_pk (pk, fpr, &fpr_len);
 1063       keyid_from_pk (pk, keyid);
 1064 
 1065       /* Compare requested and returned fingerprints if available. */
 1066       for (n = 0; n < ndesc; n++)
 1067         {
 1068           if (desc[n].mode == KEYDB_SEARCH_MODE_FPR20)
 1069             {
 1070               if (fpr_len == 20 && !memcmp (fpr, desc[n].u.fpr, 20))
 1071                 return 0;
 1072             }
 1073           else if (desc[n].mode == KEYDB_SEARCH_MODE_FPR16)
 1074             {
 1075               if (fpr_len == 16 && !memcmp (fpr, desc[n].u.fpr, 16))
 1076                 return 0;
 1077             }
 1078           else if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID)
 1079             {
 1080               if (keyid[0] == desc[n].u.kid[0] && keyid[1] == desc[n].u.kid[1])
 1081                 return 0;
 1082             }
 1083           else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID)
 1084             {
 1085               if (keyid[1] == desc[n].u.kid[1])
 1086                 return 0;
 1087             }
 1088           else /* No keyid or fingerprint - can't check.  */
 1089             return 0; /* allow import.  */
 1090         }
 1091     }
 1092 
 1093   return gpg_error (GPG_ERR_GENERAL);
 1094 }
 1095 
 1096 
 1097 int
 1098 keyserver_import (ctrl_t ctrl, strlist_t users)
 1099 {
 1100   gpg_error_t err;
 1101   KEYDB_SEARCH_DESC *desc;
 1102   int num=100,count=0;
 1103   int rc=0;
 1104 
 1105   /* Build a list of key ids */
 1106   desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
 1107 
 1108   for(;users;users=users->next)
 1109     {
 1110       err = classify_user_id (users->d, &desc[count], 1);
 1111       if (err || (desc[count].mode    != KEYDB_SEARCH_MODE_SHORT_KID
 1112                   && desc[count].mode != KEYDB_SEARCH_MODE_LONG_KID
 1113                   && desc[count].mode != KEYDB_SEARCH_MODE_FPR16
 1114                   && desc[count].mode != KEYDB_SEARCH_MODE_FPR20))
 1115     {
 1116       log_error (_("\"%s\" not a key ID: skipping\n"), users->d);
 1117       continue;
 1118     }
 1119 
 1120       count++;
 1121       if(count==num)
 1122     {
 1123       num+=100;
 1124       desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
 1125     }
 1126     }
 1127 
 1128   if(count>0)
 1129     rc = keyserver_get (ctrl, desc, count, NULL, 0, NULL, NULL);
 1130 
 1131   xfree(desc);
 1132 
 1133   return rc;
 1134 }
 1135 
 1136 
 1137 /* Return true if any keyserver has been configured. */
 1138 int
 1139 keyserver_any_configured (ctrl_t ctrl)
 1140 {
 1141   return !gpg_dirmngr_ks_list (ctrl, NULL);
 1142 }
 1143 
 1144 
 1145 /* Import all keys that exactly match NAME */
 1146 int
 1147 keyserver_import_name (ctrl_t ctrl, const char *name,
 1148                        unsigned char **fpr, size_t *fprlen,
 1149                        struct keyserver_spec *keyserver)
 1150 {
 1151   KEYDB_SEARCH_DESC desc;
 1152 
 1153   memset (&desc, 0, sizeof desc);
 1154 
 1155   desc.mode = KEYDB_SEARCH_MODE_EXACT;
 1156   desc.u.name = name;
 1157 
 1158   return keyserver_get (ctrl, &desc, 1, keyserver, 0, fpr, fprlen);
 1159 }
 1160 
 1161 
 1162 int
 1163 keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len,
 1164              struct keyserver_spec *keyserver, int quick)
 1165 {
 1166   KEYDB_SEARCH_DESC desc;
 1167 
 1168   memset(&desc,0,sizeof(desc));
 1169 
 1170   if(fprint_len==16)
 1171     desc.mode=KEYDB_SEARCH_MODE_FPR16;
 1172   else if(fprint_len==20)
 1173     desc.mode=KEYDB_SEARCH_MODE_FPR20;
 1174   else
 1175     return -1;
 1176 
 1177   memcpy(desc.u.fpr,fprint,fprint_len);
 1178 
 1179   /* TODO: Warn here if the fingerprint we got doesn't match the one
 1180      we asked for? */
 1181   return keyserver_get (ctrl, &desc, 1, keyserver, quick, NULL, NULL);
 1182 }
 1183 
 1184 int
 1185 keyserver_import_keyid (ctrl_t ctrl,
 1186                         u32 *keyid,struct keyserver_spec *keyserver, int quick)
 1187 {
 1188   KEYDB_SEARCH_DESC desc;
 1189 
 1190   memset(&desc,0,sizeof(desc));
 1191 
 1192   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
 1193   desc.u.kid[0]=keyid[0];
 1194   desc.u.kid[1]=keyid[1];
 1195 
 1196   return keyserver_get (ctrl, &desc, 1, keyserver, quick, NULL, NULL);
 1197 }
 1198 
 1199 
 1200 /* code mostly stolen from do_export_stream */
 1201 static int
 1202 keyidlist (ctrl_t ctrl, strlist_t users, KEYDB_SEARCH_DESC **klist,
 1203            int *count, int fakev3)
 1204 {
 1205   int rc = 0;
 1206   int num = 100;
 1207   kbnode_t keyblock = NULL;
 1208   kbnode_t node;
 1209   KEYDB_HANDLE kdbhd;
 1210   int ndesc;
 1211   KEYDB_SEARCH_DESC *desc = NULL;
 1212   strlist_t sl;
 1213 
 1214   *count=0;
 1215 
 1216   *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
 1217 
 1218   kdbhd = keydb_new ();
 1219   if (!kdbhd)
 1220     {
 1221       rc = gpg_error_from_syserror ();
 1222       goto leave;
 1223     }
 1224   keydb_disable_caching (kdbhd);  /* We are looping the search.  */
 1225 
 1226   if(!users)
 1227     {
 1228       ndesc = 1;
 1229       desc = xmalloc_clear ( ndesc * sizeof *desc);
 1230       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
 1231     }
 1232   else
 1233     {
 1234       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
 1235     ;
 1236       desc = xmalloc ( ndesc * sizeof *desc);
 1237 
 1238       for (ndesc=0, sl=users; sl; sl = sl->next)
 1239     {
 1240           gpg_error_t err;
 1241       if (!(err = classify_user_id (sl->d, desc+ndesc, 1)))
 1242         ndesc++;
 1243       else
 1244         log_error (_("key \"%s\" not found: %s\n"),
 1245                sl->d, gpg_strerror (err));
 1246     }
 1247     }
 1248 
 1249   for (;;)
 1250     {
 1251       rc = keydb_search (kdbhd, desc, ndesc, NULL);
 1252       if (rc)
 1253         break;  /* ready.  */
 1254 
 1255       if (!users)
 1256     desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
 1257 
 1258       /* read the keyblock */
 1259       rc = keydb_get_keyblock (kdbhd, &keyblock );
 1260       if( rc )
 1261     {
 1262           log_error (_("error reading keyblock: %s\n"), gpg_strerror (rc) );
 1263       goto leave;
 1264     }
 1265 
 1266       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
 1267     {
 1268       /* This is to work around a bug in some keyservers (pksd and
 1269              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
 1270              The answer is to refresh both the correct v4 keyid
 1271              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
 1272              This only happens for key refresh using the HKP scheme
 1273              and if the refresh-add-fake-v3-keyids keyserver option is
 1274              set. */
 1275       if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
 1276          node->pkt->pkt.public_key->version>=4)
 1277         {
 1278           (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
 1279           v3_keyid (node->pkt->pkt.public_key->pkey[0],
 1280                         (*klist)[*count].u.kid);
 1281           (*count)++;
 1282 
 1283           if(*count==num)
 1284         {
 1285           num+=100;
 1286           *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
 1287         }
 1288         }
 1289 
 1290       /* v4 keys get full fingerprints.  v3 keys get long keyids.
 1291              This is because it's easy to calculate any sort of keyid
 1292              from a v4 fingerprint, but not a v3 fingerprint. */
 1293 
 1294       if(node->pkt->pkt.public_key->version<4)
 1295         {
 1296           (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
 1297           keyid_from_pk(node->pkt->pkt.public_key,
 1298                 (*klist)[*count].u.kid);
 1299         }
 1300       else
 1301         {
 1302           size_t dummy;
 1303 
 1304           (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
 1305           fingerprint_from_pk(node->pkt->pkt.public_key,
 1306                   (*klist)[*count].u.fpr,&dummy);
 1307         }
 1308 
 1309       /* This is a little hackish, using the skipfncvalue as a
 1310          void* pointer to the keyserver spec, but we don't need
 1311          the skipfnc here, and it saves having an additional field
 1312          for this (which would be wasted space most of the
 1313          time). */
 1314 
 1315       (*klist)[*count].skipfncvalue=NULL;
 1316 
 1317       /* Are we honoring preferred keyservers? */
 1318       if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
 1319         {
 1320           PKT_user_id *uid=NULL;
 1321           PKT_signature *sig=NULL;
 1322 
 1323           merge_keys_and_selfsig (ctrl, keyblock);
 1324 
 1325           for(node=node->next;node;node=node->next)
 1326         {
 1327           if(node->pkt->pkttype==PKT_USER_ID
 1328              && node->pkt->pkt.user_id->flags.primary)
 1329             uid=node->pkt->pkt.user_id;
 1330           else if(node->pkt->pkttype==PKT_SIGNATURE
 1331               && node->pkt->pkt.signature->
 1332               flags.chosen_selfsig && uid)
 1333             {
 1334               sig=node->pkt->pkt.signature;
 1335               break;
 1336             }
 1337         }
 1338 
 1339           /* Try and parse the keyserver URL.  If it doesn't work,
 1340          then we end up writing NULL which indicates we are
 1341          the same as any other key. */
 1342           if(sig)
 1343         (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
 1344         }
 1345 
 1346       (*count)++;
 1347 
 1348       if(*count==num)
 1349         {
 1350           num+=100;
 1351           *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
 1352         }
 1353     }
 1354     }
 1355 
 1356   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
 1357     rc = 0;
 1358 
 1359  leave:
 1360   if(rc)
 1361     {
 1362       xfree(*klist);
 1363       *klist = NULL;
 1364     }
 1365   xfree(desc);
 1366   keydb_release(kdbhd);
 1367   release_kbnode(keyblock);
 1368 
 1369   return rc;
 1370 }
 1371 
 1372 /* Note this is different than the original HKP refresh.  It allows
 1373    usernames to refresh only part of the keyring. */
 1374 
 1375 gpg_error_t
 1376 keyserver_refresh (ctrl_t ctrl, strlist_t users)
 1377 {
 1378   gpg_error_t err;
 1379   int count, numdesc;
 1380   int fakev3 = 0;
 1381   KEYDB_SEARCH_DESC *desc;
 1382   unsigned int options=opt.keyserver_options.import_options;
 1383 
 1384   /* We switch merge-only on during a refresh, as 'refresh' should
 1385      never import new keys, even if their keyids match. */
 1386   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
 1387 
 1388   /* Similarly, we switch on fast-import, since refresh may make
 1389      multiple import sets (due to preferred keyserver URLs).  We don't
 1390      want each set to rebuild the trustdb.  Instead we do it once at
 1391      the end here. */
 1392   opt.keyserver_options.import_options|=IMPORT_FAST;
 1393 
 1394   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
 1395      scheme, then enable fake v3 keyid generation.  Note that this
 1396      works only with a keyserver configured. gpg.conf
 1397      (i.e. opt.keyserver); however that method of configuring a
 1398      keyserver is deprecated and in any case it is questionable
 1399      whether we should keep on supporting these ancient and broken
 1400      keyservers.  */
 1401   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
 1402      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
 1403      ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
 1404     fakev3=1;
 1405 
 1406   err = keyidlist (ctrl, users, &desc, &numdesc, fakev3);
 1407   if (err)
 1408     return err;
 1409 
 1410   count=numdesc;
 1411   if(count>0)
 1412     {
 1413       int i;
 1414 
 1415       /* Try to handle preferred keyserver keys first */
 1416       for(i=0;i<numdesc;i++)
 1417     {
 1418       if(desc[i].skipfncvalue)
 1419         {
 1420           struct keyserver_spec *keyserver=desc[i].skipfncvalue;
 1421 
 1422               if (!opt.quiet)
 1423                 log_info (_("refreshing %d key from %s\n"), 1, keyserver->uri);
 1424 
 1425           /* We use the keyserver structure we parsed out before.
 1426          Note that a preferred keyserver without a scheme://
 1427          will be interpreted as hkp:// */
 1428           err = keyserver_get (ctrl, &desc[i], 1, keyserver, 0, NULL, NULL);
 1429           if (err)
 1430         log_info(_("WARNING: unable to refresh key %s"
 1431                " via %s: %s\n"),keystr_from_desc(&desc[i]),
 1432              keyserver->uri,gpg_strerror (err));
 1433           else
 1434         {
 1435           /* We got it, so mark it as NONE so we don't try and
 1436              get it again from the regular keyserver. */
 1437 
 1438           desc[i].mode=KEYDB_SEARCH_MODE_NONE;
 1439           count--;
 1440         }
 1441 
 1442           free_keyserver_spec(keyserver);
 1443         }
 1444     }
 1445     }
 1446 
 1447   if(count>0)
 1448     {
 1449       char *tmpuri;
 1450 
 1451       err = gpg_dirmngr_ks_list (ctrl, &tmpuri);
 1452       if (!err)
 1453         {
 1454           if (!opt.quiet)
 1455             {
 1456               log_info (ngettext("refreshing %d key from %s\n",
 1457                                  "refreshing %d keys from %s\n",
 1458                                  count), count, tmpuri);
 1459             }
 1460           xfree (tmpuri);
 1461 
 1462           err = keyserver_get (ctrl, desc, numdesc, NULL, 0, NULL, NULL);
 1463         }
 1464     }
 1465 
 1466   xfree(desc);
 1467 
 1468   opt.keyserver_options.import_options=options;
 1469 
 1470   /* If the original options didn't have fast import, and the trustdb
 1471      is dirty, rebuild. */
 1472   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
 1473     check_or_update_trustdb (ctrl);
 1474 
 1475   return err;
 1476 }
 1477 
 1478 
 1479 /* Search for keys on the keyservers.  The patterns are given in the
 1480    string list TOKENS.  */
 1481 gpg_error_t
 1482 keyserver_search (ctrl_t ctrl, strlist_t tokens)
 1483 {
 1484   gpg_error_t err;
 1485   char *searchstr;
 1486   struct search_line_handler_parm_s parm;
 1487 
 1488   memset (&parm, 0, sizeof parm);
 1489 
 1490   if (!tokens)
 1491     return 0;  /* Return success if no patterns are given.  */
 1492 
 1493   /* Write global options */
 1494 
 1495   /* for(temp=opt.keyserver_options.other;temp;temp=temp->next) */
 1496   /*   es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */
 1497 
 1498   /* Write per-keyserver options */
 1499 
 1500   /* for(temp=keyserver->options;temp;temp=temp->next) */
 1501   /*   es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */
 1502 
 1503   {
 1504     membuf_t mb;
 1505     strlist_t item;
 1506 
 1507     init_membuf (&mb, 1024);
 1508     for (item = tokens; item; item = item->next)
 1509     {
 1510       if (item != tokens)
 1511         put_membuf (&mb, " ", 1);
 1512       put_membuf_str (&mb, item->d);
 1513     }
 1514     put_membuf (&mb, "", 1); /* Append Nul.  */
 1515     searchstr = get_membuf (&mb, NULL);
 1516     if (!searchstr)
 1517       {
 1518         err = gpg_error_from_syserror ();
 1519         goto leave;
 1520       }
 1521   }
 1522   /* FIXME: Enable the next line */
 1523   /* log_info (_("searching for \"%s\" from %s\n"), searchstr, keyserver->uri); */
 1524 
 1525   parm.ctrl = ctrl;
 1526   if (searchstr)
 1527     parm.searchstr_disp = utf8_to_native (searchstr, strlen (searchstr), 0);
 1528 
 1529   err = gpg_dirmngr_ks_search (ctrl, searchstr, search_line_handler, &parm);
 1530 
 1531   if (parm.not_found || gpg_err_code (err) == GPG_ERR_NO_DATA)
 1532     {
 1533       if (parm.searchstr_disp)
 1534         log_info (_("key \"%s\" not found on keyserver\n"),
 1535                   parm.searchstr_disp);
 1536       else
 1537         log_info (_("key not found on keyserver\n"));
 1538     }
 1539 
 1540   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
 1541     err = gpg_error (GPG_ERR_NOT_FOUND);
 1542   else if (err)
 1543     log_error ("error searching keyserver: %s\n", gpg_strerror (err));
 1544 
 1545   /* switch(ret) */
 1546   /*   { */
 1547   /*   case KEYSERVER_SCHEME_NOT_FOUND: */
 1548   /*     log_error(_("no handler for keyserver scheme '%s'\n"), */
 1549   /*        opt.keyserver->scheme); */
 1550   /*     break; */
 1551 
 1552   /*   case KEYSERVER_NOT_SUPPORTED: */
 1553   /*     log_error(_("action '%s' not supported with keyserver " */
 1554   /*          "scheme '%s'\n"), "search", opt.keyserver->scheme); */
 1555   /*     break; */
 1556 
 1557   /*   case KEYSERVER_TIMEOUT: */
 1558   /*     log_error(_("keyserver timed out\n")); */
 1559   /*     break; */
 1560 
 1561   /*   case KEYSERVER_INTERNAL_ERROR: */
 1562   /*   default: */
 1563   /*     log_error(_("keyserver internal error\n")); */
 1564   /*     break; */
 1565   /*   } */
 1566 
 1567   /* return gpg_error (GPG_ERR_KEYSERVER); */
 1568 
 1569 
 1570  leave:
 1571   xfree (parm.desc);
 1572   xfree (parm.searchstr_disp);
 1573   xfree(searchstr);
 1574 
 1575   return err;
 1576 }
 1577 
 1578 /* Helper for keyserver_get.  Here we only receive a chunk of the
 1579    description to be processed in one batch.  This is required due to
 1580    the limited number of patterns the dirmngr interface (KS_GET) can
 1581    grok and to limit the amount of temporary required memory.  */
 1582 static gpg_error_t
 1583 keyserver_get_chunk (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc,
 1584                      int *r_ndesc_used,
 1585                      import_stats_t stats_handle,
 1586                      struct keyserver_spec *override_keyserver,
 1587                      int quick,
 1588                      unsigned char **r_fpr, size_t *r_fprlen)
 1589 
 1590 {
 1591   gpg_error_t err = 0;
 1592   char **pattern;
 1593   int idx, npat, npat_fpr;
 1594   estream_t datastream;
 1595   char *source = NULL;
 1596   size_t linelen;  /* Estimated linelen for KS_GET.  */
 1597   size_t n;
 1598   int only_fprs;
 1599 
 1600 #define MAX_KS_GET_LINELEN 950  /* Somewhat lower than the real limit.  */
 1601 
 1602   *r_ndesc_used = 0;
 1603 
 1604   /* Create an array filled with a search pattern for each key.  The
 1605      array is delimited by a NULL entry.  */
 1606   pattern = xtrycalloc (ndesc+1, sizeof *pattern);
 1607   if (!pattern)
 1608     return gpg_error_from_syserror ();
 1609 
 1610   /* Note that we break the loop as soon as our estimation of the to
 1611      be used line length reaches the limit.  But we do this only if we
 1612      have processed at least one search requests so that an overlong
 1613      single request will be rejected only later by gpg_dirmngr_ks_get
 1614      but we are sure that R_NDESC_USED has been updated.  This avoids
 1615      a possible indefinite loop.  */
 1616   linelen = 17; /* "KS_GET --quick --" */
 1617   for (npat=npat_fpr=0, idx=0; idx < ndesc; idx++)
 1618     {
 1619       int quiet = 0;
 1620 
 1621       if (desc[idx].mode == KEYDB_SEARCH_MODE_FPR20
 1622           || desc[idx].mode == KEYDB_SEARCH_MODE_FPR16)
 1623         {
 1624           n = 1+2+2*20;
 1625           if (idx && linelen + n > MAX_KS_GET_LINELEN)
 1626             break; /* Declare end of this chunk.  */
 1627           linelen += n;
 1628 
 1629           pattern[npat] = xtrymalloc (n);
 1630           if (!pattern[npat])
 1631             err = gpg_error_from_syserror ();
 1632           else
 1633             {
 1634               strcpy (pattern[npat], "0x");
 1635               bin2hex (desc[idx].u.fpr,
 1636                        desc[idx].mode == KEYDB_SEARCH_MODE_FPR20? 20 : 16,
 1637                        pattern[npat]+2);
 1638               npat++;
 1639               if (desc[idx].mode == KEYDB_SEARCH_MODE_FPR20)
 1640                 npat_fpr++;
 1641             }
 1642         }
 1643       else if(desc[idx].mode == KEYDB_SEARCH_MODE_LONG_KID)
 1644         {
 1645           n = 1+2+16;
 1646           if (idx && linelen + n > MAX_KS_GET_LINELEN)
 1647             break; /* Declare end of this chunk.  */
 1648           linelen += n;
 1649 
 1650           pattern[npat] = xtryasprintf ("0x%08lX%08lX",
 1651                                         (ulong)desc[idx].u.kid[0],
 1652                                         (ulong)desc[idx].u.kid[1]);
 1653           if (!pattern[npat])
 1654             err = gpg_error_from_syserror ();
 1655           else
 1656             npat++;
 1657         }
 1658       else if(desc[idx].mode == KEYDB_SEARCH_MODE_SHORT_KID)
 1659         {
 1660           n = 1+2+8;
 1661           if (idx && linelen + n > MAX_KS_GET_LINELEN)
 1662             break; /* Declare end of this chunk.  */
 1663           linelen += n;
 1664 
 1665           pattern[npat] = xtryasprintf ("0x%08lX", (ulong)desc[idx].u.kid[1]);
 1666           if (!pattern[npat])
 1667             err = gpg_error_from_syserror ();
 1668           else
 1669             npat++;
 1670         }
 1671       else if(desc[idx].mode == KEYDB_SEARCH_MODE_EXACT)
 1672         {
 1673           /* The Dirmngr also uses classify_user_id to detect the type
 1674              of the search string.  By adding the '=' prefix we force
 1675              Dirmngr's KS_GET to consider this an exact search string.
 1676              (In gpg 1.4 and gpg 2.0 the keyserver helpers used the
 1677              KS_GETNAME command to indicate this.)  */
 1678 
 1679           n = 1+1+strlen (desc[idx].u.name);
 1680           if (idx && linelen + n > MAX_KS_GET_LINELEN)
 1681             break; /* Declare end of this chunk.  */
 1682           linelen += n;
 1683 
 1684           pattern[npat] = strconcat ("=", desc[idx].u.name, NULL);
 1685           if (!pattern[npat])
 1686             err = gpg_error_from_syserror ();
 1687           else
 1688             {
 1689               npat++;
 1690               quiet = 1;
 1691             }
 1692         }
 1693       else if (desc[idx].mode == KEYDB_SEARCH_MODE_NONE)
 1694         continue;
 1695       else
 1696         BUG();
 1697 
 1698       if (err)
 1699         {
 1700           for (idx=0; idx < npat; idx++)
 1701             xfree (pattern[idx]);
 1702           xfree (pattern);
 1703           return err;
 1704         }
 1705 
 1706       if (!quiet && override_keyserver)
 1707         {
 1708           if (override_keyserver->host)
 1709             log_info (_("requesting key %s from %s server %s\n"),
 1710                       keystr_from_desc (&desc[idx]),
 1711                       override_keyserver->scheme, override_keyserver->host);
 1712           else
 1713             log_info (_("requesting key %s from %s\n"),
 1714                       keystr_from_desc (&desc[idx]), override_keyserver->uri);
 1715         }
 1716     }
 1717 
 1718   /* Remember now many of search items were considered.  Note that
 1719      this is different from NPAT.  */
 1720   *r_ndesc_used = idx;
 1721 
 1722   only_fprs = (npat && npat == npat_fpr);
 1723 
 1724   err = gpg_dirmngr_ks_get (ctrl, pattern, override_keyserver, quick,
 1725                             &datastream, &source);
 1726   for (idx=0; idx < npat; idx++)
 1727     xfree (pattern[idx]);
 1728   xfree (pattern);
 1729   if (opt.verbose && source)
 1730     log_info ("data source: %s\n", source);
 1731 
 1732   if (!err)
 1733     {
 1734       struct ks_retrieval_screener_arg_s screenerarg;
 1735 
 1736       /* FIXME: Check whether this comment should be moved to dirmngr.
 1737 
 1738          Slurp up all the key data.  In the future, it might be nice
 1739          to look for KEY foo OUTOFBAND and FAILED indicators.  It's
 1740          harmless to ignore them, but ignoring them does make gpg
 1741          complain about "no valid OpenPGP data found".  One way to do
 1742          this could be to continue parsing this line-by-line and make
 1743          a temp iobuf for each key.  Note that we don't allow the
 1744          import of secret keys from a keyserver.  Keyservers should
 1745          never accept or send them but we better protect against rogue
 1746          keyservers. */
 1747 
 1748       screenerarg.desc = desc;
 1749       screenerarg.ndesc = *r_ndesc_used;
 1750       import_keys_es_stream (ctrl, datastream, stats_handle,
 1751                              r_fpr, r_fprlen,
 1752                              (opt.keyserver_options.import_options
 1753                               | IMPORT_NO_SECKEY),
 1754                              keyserver_retrieval_screener, &screenerarg,
 1755                              only_fprs? KEYORG_KS : 0,
 1756                              source);
 1757     }
 1758   es_fclose (datastream);
 1759   xfree (source);
 1760 
 1761   return err;
 1762 }
 1763 
 1764 
 1765 /* Retrieve a key from a keyserver.  The search pattern are in
 1766    (DESC,NDESC).  Allowed search modes are keyid, fingerprint, and
 1767    exact searches.  OVERRIDE_KEYSERVER gives an optional override
 1768    keyserver. If (R_FPR,R_FPRLEN) are not NULL, they may return the
 1769    fingerprint of a single imported key.  If QUICK is set, dirmngr is
 1770    advised to use a shorter timeout. */
 1771 static gpg_error_t
 1772 keyserver_get (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc,
 1773                struct keyserver_spec *override_keyserver, int quick,
 1774                unsigned char **r_fpr, size_t *r_fprlen)
 1775 {
 1776   gpg_error_t err;
 1777   import_stats_t stats_handle;
 1778   int ndesc_used;
 1779   int any_good = 0;
 1780 
 1781   stats_handle = import_new_stats_handle();
 1782 
 1783   for (;;)
 1784     {
 1785       err = keyserver_get_chunk (ctrl, desc, ndesc, &ndesc_used, stats_handle,
 1786                                  override_keyserver, quick, r_fpr, r_fprlen);
 1787       if (!err)
 1788         any_good = 1;
 1789       if (err || ndesc_used >= ndesc)
 1790         break; /* Error or all processed.  */
 1791       /* Prepare for the next chunk.  */
 1792       desc += ndesc_used;
 1793       ndesc -= ndesc_used;
 1794     }
 1795 
 1796   if (any_good)
 1797     import_print_stats (stats_handle);
 1798 
 1799   import_release_stats_handle (stats_handle);
 1800   return err;
 1801 }
 1802 
 1803 
 1804 /* Send all keys specified by KEYSPECS to the configured keyserver.  */
 1805 static gpg_error_t
 1806 keyserver_put (ctrl_t ctrl, strlist_t keyspecs)
 1807 
 1808 {
 1809   gpg_error_t err;
 1810   strlist_t kspec;
 1811   char *ksurl;
 1812 
 1813   if (!keyspecs)
 1814     return 0;  /* Return success if the list is empty.  */
 1815 
 1816   if (gpg_dirmngr_ks_list (ctrl, &ksurl))
 1817     {
 1818       log_error (_("no keyserver known\n"));
 1819       return gpg_error (GPG_ERR_NO_KEYSERVER);
 1820     }
 1821 
 1822   for (kspec = keyspecs; kspec; kspec = kspec->next)
 1823     {
 1824       void *data;
 1825       size_t datalen;
 1826       kbnode_t keyblock;
 1827 
 1828       err = export_pubkey_buffer (ctrl, kspec->d,
 1829                                   opt.keyserver_options.export_options,
 1830                                   NULL,
 1831                                   &keyblock, &data, &datalen);
 1832       if (err)
 1833         log_error (_("skipped \"%s\": %s\n"), kspec->d, gpg_strerror (err));
 1834       else
 1835         {
 1836           log_info (_("sending key %s to %s\n"),
 1837                     keystr (keyblock->pkt->pkt.public_key->keyid),
 1838                     ksurl?ksurl:"[?]");
 1839 
 1840           err = gpg_dirmngr_ks_put (ctrl, data, datalen, keyblock);
 1841           release_kbnode (keyblock);
 1842           xfree (data);
 1843           if (err)
 1844             {
 1845               write_status_error ("keyserver_send", err);
 1846               log_error (_("keyserver send failed: %s\n"), gpg_strerror (err));
 1847             }
 1848         }
 1849     }
 1850 
 1851   xfree (ksurl);
 1852 
 1853   return err;
 1854 
 1855 }
 1856 
 1857 
 1858 /* Loop over all URLs in STRLIST and fetch the key at that URL.  Note
 1859    that the fetch operation ignores the configured keyservers and
 1860    instead directly retrieves the keys.  */
 1861 int
 1862 keyserver_fetch (ctrl_t ctrl, strlist_t urilist, int origin)
 1863 {
 1864   gpg_error_t err;
 1865   strlist_t sl;
 1866   estream_t datastream;
 1867   unsigned int save_options = opt.keyserver_options.import_options;
 1868 
 1869   /* Switch on fast-import, since fetch can handle more than one
 1870      import and we don't want each set to rebuild the trustdb.
 1871      Instead we do it once at the end. */
 1872   opt.keyserver_options.import_options |= IMPORT_FAST;
 1873 
 1874   for (sl=urilist; sl; sl=sl->next)
 1875     {
 1876       if (!opt.quiet)
 1877         log_info (_("requesting key from '%s'\n"), sl->d);
 1878 
 1879       err = gpg_dirmngr_ks_fetch (ctrl, sl->d, &datastream);
 1880       if (!err)
 1881         {
 1882           import_stats_t stats_handle;
 1883 
 1884           stats_handle = import_new_stats_handle();
 1885           import_keys_es_stream (ctrl, datastream, stats_handle, NULL, NULL,
 1886                                  opt.keyserver_options.import_options,
 1887                                  NULL, NULL, origin, sl->d);
 1888 
 1889           import_print_stats (stats_handle);
 1890           import_release_stats_handle (stats_handle);
 1891         }
 1892       else
 1893         log_info (_("WARNING: unable to fetch URI %s: %s\n"),
 1894                   sl->d, gpg_strerror (err));
 1895       es_fclose (datastream);
 1896     }
 1897 
 1898   opt.keyserver_options.import_options = save_options;
 1899 
 1900   /* If the original options didn't have fast import, and the trustdb
 1901      is dirty, rebuild. */
 1902   if (!(opt.keyserver_options.import_options&IMPORT_FAST))
 1903     check_or_update_trustdb (ctrl);
 1904 
 1905   return 0;
 1906 }
 1907 
 1908 
 1909 /* Import key in a CERT or pointed to by a CERT.  In DANE_MODE fetch
 1910    the certificate using the DANE method.  */
 1911 int
 1912 keyserver_import_cert (ctrl_t ctrl, const char *name, int dane_mode,
 1913                        unsigned char **fpr,size_t *fpr_len)
 1914 {
 1915   gpg_error_t err;
 1916   char *look,*url;
 1917   estream_t key;
 1918 
 1919   look = xstrdup(name);
 1920 
 1921   if (!dane_mode)
 1922     {
 1923       char *domain = strrchr (look,'@');
 1924       if (domain)
 1925         *domain='.';
 1926     }
 1927 
 1928   err = gpg_dirmngr_dns_cert (ctrl, look, dane_mode? NULL : "*",
 1929                               &key, fpr, fpr_len, &url);
 1930   if (err)
 1931     ;
 1932   else if (key)
 1933     {
 1934       int armor_status=opt.no_armor;
 1935       import_filter_t save_filt;
 1936 
 1937       /* CERTs and DANE records are always in binary format */
 1938       opt.no_armor=1;
 1939       if (dane_mode)
 1940         {
 1941           save_filt = save_and_clear_import_filter ();
 1942           if (!save_filt)
 1943             err = gpg_error_from_syserror ();
 1944           else
 1945             {
 1946               char *filtstr = es_bsprintf ("keep-uid=mbox = %s", look);
 1947               err = filtstr? 0 : gpg_error_from_syserror ();
 1948               if (!err)
 1949                 err = parse_and_set_import_filter (filtstr);
 1950               xfree (filtstr);
 1951               if (!err)
 1952                 err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len,
 1953                                              IMPORT_NO_SECKEY,
 1954                                              NULL, NULL, KEYORG_DANE, NULL);
 1955               restore_import_filter (save_filt);
 1956             }
 1957         }
 1958       else
 1959         {
 1960           err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len,
 1961                                        (opt.keyserver_options.import_options
 1962                                         | IMPORT_NO_SECKEY),
 1963                                        NULL, NULL, 0, NULL);
 1964         }
 1965 
 1966       opt.no_armor=armor_status;
 1967 
 1968       es_fclose (key);
 1969       key = NULL;
 1970     }
 1971   else if (*fpr)
 1972     {
 1973       /* We only consider the IPGP type if a fingerprint was provided.
 1974      This lets us select the right key regardless of what a URL
 1975      points to, or get the key from a keyserver. */
 1976       if(url)
 1977     {
 1978       struct keyserver_spec *spec;
 1979 
 1980       spec = parse_keyserver_uri (url, 1);
 1981       if(spec)
 1982         {
 1983           err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, spec, 0);
 1984           free_keyserver_spec(spec);
 1985         }
 1986     }
 1987       else if (keyserver_any_configured (ctrl))
 1988     {
 1989       /* If only a fingerprint is provided, try and fetch it from
 1990          the configured keyserver. */
 1991 
 1992       err = keyserver_import_fprint (ctrl,
 1993                                          *fpr, *fpr_len, opt.keyserver, 0);
 1994     }
 1995       else
 1996     log_info(_("no keyserver known\n"));
 1997 
 1998       /* Give a better string here? "CERT fingerprint for \"%s\"
 1999      found, but no keyserver" " known (use option
 2000      --keyserver)\n" ? */
 2001 
 2002     }
 2003 
 2004   xfree(url);
 2005   xfree(look);
 2006 
 2007   return err;
 2008 }
 2009 
 2010 /* Import key pointed to by a PKA record. Return the requested
 2011    fingerprint in fpr. */
 2012 gpg_error_t
 2013 keyserver_import_pka (ctrl_t ctrl, const char *name,
 2014                       unsigned char **fpr, size_t *fpr_len)
 2015 {
 2016   gpg_error_t err;
 2017   char *url;
 2018 
 2019   err = gpg_dirmngr_get_pka (ctrl, name, fpr, fpr_len, &url);
 2020   if (url && *url && fpr && fpr_len)
 2021     {
 2022       /* An URL is available.  Lookup the key. */
 2023       struct keyserver_spec *spec;
 2024       spec = parse_keyserver_uri (url, 1);
 2025       if (spec)
 2026     {
 2027       err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, spec, 0);
 2028       free_keyserver_spec (spec);
 2029     }
 2030     }
 2031   xfree (url);
 2032 
 2033   if (err)
 2034     {
 2035       xfree(*fpr);
 2036       *fpr = NULL;
 2037       *fpr_len = 0;
 2038     }
 2039 
 2040   return err;
 2041 }
 2042 
 2043 
 2044 /* Import a key using the Web Key Directory protocol.  */
 2045 gpg_error_t
 2046 keyserver_import_wkd (ctrl_t ctrl, const char *name, int quick,
 2047                       unsigned char **fpr, size_t *fpr_len)
 2048 {
 2049   gpg_error_t err;
 2050   char *mbox;
 2051   estream_t key;
 2052   char *url = NULL;
 2053 
 2054   /* We want to work on the mbox.  That is what dirmngr will do anyway
 2055    * and we need the mbox for the import filter anyway.  */
 2056   mbox = mailbox_from_userid (name);
 2057   if (!mbox)
 2058     {
 2059       err = gpg_error_from_syserror ();
 2060       if (gpg_err_code (err) == GPG_ERR_EINVAL)
 2061         err = gpg_error (GPG_ERR_INV_USER_ID);
 2062       return err;
 2063     }
 2064 
 2065   err = gpg_dirmngr_wkd_get (ctrl, mbox, quick, &key, &url);
 2066   if (err)
 2067     ;
 2068   else if (key)
 2069     {
 2070       int armor_status = opt.no_armor;
 2071       import_filter_t save_filt;
 2072 
 2073       /* Keys returned via WKD are in binary format.  However, we
 2074        * relax that requirement and allow also for armored data.  */
 2075       opt.no_armor = 0;
 2076       save_filt = save_and_clear_import_filter ();
 2077       if (!save_filt)
 2078         err = gpg_error_from_syserror ();
 2079       else
 2080         {
 2081           char *filtstr = es_bsprintf ("keep-uid=mbox = %s", mbox);
 2082           err = filtstr? 0 : gpg_error_from_syserror ();
 2083           if (!err)
 2084             err = parse_and_set_import_filter (filtstr);
 2085           xfree (filtstr);
 2086           if (!err)
 2087             err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len,
 2088                                          IMPORT_NO_SECKEY,
 2089                                          NULL, NULL, KEYORG_WKD, url);
 2090 
 2091         }
 2092 
 2093       restore_import_filter (save_filt);
 2094       opt.no_armor = armor_status;
 2095 
 2096       es_fclose (key);
 2097       key = NULL;
 2098     }
 2099 
 2100   xfree (url);
 2101   xfree (mbox);
 2102   return err;
 2103 }
 2104 
 2105 
 2106 /* Import a key by name using LDAP */
 2107 int
 2108 keyserver_import_ldap (ctrl_t ctrl,
 2109                        const char *name, unsigned char **fpr, size_t *fprlen)
 2110 {
 2111   (void)ctrl;
 2112   (void)name;
 2113   (void)fpr;
 2114   (void)fprlen;
 2115   return gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/
 2116 #if 0
 2117   char *domain;
 2118   struct keyserver_spec *keyserver;
 2119   strlist_t list=NULL;
 2120   int rc,hostlen=1;
 2121   struct srventry *srvlist=NULL;
 2122   int srvcount,i;
 2123   char srvname[MAXDNAME];
 2124 
 2125   /* Parse out the domain */
 2126   domain=strrchr(name,'@');
 2127   if(!domain)
 2128     return GPG_ERR_GENERAL;
 2129 
 2130   domain++;
 2131 
 2132   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
 2133   keyserver->scheme=xstrdup("ldap");
 2134   keyserver->host=xmalloc(1);
 2135   keyserver->host[0]='\0';
 2136 
 2137   snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
 2138 
 2139   FIXME("network related - move to dirmngr or drop the code");
 2140   srvcount=getsrv(srvname,&srvlist);
 2141 
 2142   for(i=0;i<srvcount;i++)
 2143     {
 2144       hostlen+=strlen(srvlist[i].target)+1;
 2145       keyserver->host=xrealloc(keyserver->host,hostlen);
 2146 
 2147       strcat(keyserver->host,srvlist[i].target);
 2148 
 2149       if(srvlist[i].port!=389)
 2150     {
 2151       char port[7];
 2152 
 2153       hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
 2154       keyserver->host=xrealloc(keyserver->host,hostlen);
 2155 
 2156       snprintf(port,7,":%u",srvlist[i].port);
 2157       strcat(keyserver->host,port);
 2158     }
 2159 
 2160       strcat(keyserver->host," ");
 2161     }
 2162 
 2163   free(srvlist);
 2164 
 2165   /* If all else fails, do the PGP Universal trick of
 2166      ldap://keys.(domain) */
 2167 
 2168   hostlen+=5+strlen(domain);
 2169   keyserver->host=xrealloc(keyserver->host,hostlen);
 2170   strcat(keyserver->host,"keys.");
 2171   strcat(keyserver->host,domain);
 2172 
 2173   append_to_strlist(&list,name);
 2174 
 2175   rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/
 2176        /* keyserver_work (ctrl, KS_GETNAME, list, NULL, */
 2177        /*                 0, fpr, fpr_len, keyserver); */
 2178 
 2179   free_strlist(list);
 2180 
 2181   free_keyserver_spec(keyserver);
 2182 
 2183   return rc;
 2184 #endif
 2185 }