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

Generated by: LCOV version 1.11