LCOV - code coverage report
Current view: top level - g10 - keyserver.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 51 844 6.0 %
Date: 2016-12-01 18:37:21 Functions: 2 29 6.9 %

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

Generated by: LCOV version 1.11