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