gpg: Fix --version output and explicitly disable ECC.
[gnupg.git] / g10 / keyserver.c
1 /* keyserver.c - generic keyserver code
2  * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3  *               2009, 2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <assert.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 "dns-cert.h"
44 #include "pka.h"
45 #ifdef USE_DNS_SRV
46 #include "srv.h"
47 #endif
48
49 #ifdef HAVE_W32_SYSTEM
50 /* It seems Vista doesn't grok X_OK and so fails access() tests.
51    Previous versions interpreted X_OK as F_OK anyway, so we'll just
52    use F_OK directly. */
53 #undef X_OK
54 #define X_OK F_OK
55 #endif /* HAVE_W32_SYSTEM */
56
57 struct keyrec
58 {
59   KEYDB_SEARCH_DESC desc;
60   u32 createtime,expiretime;
61   int size,flags;
62   byte type;
63   IOBUF uidbuf;
64   unsigned int lines;
65 };
66
67 enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH};
68
69 static struct parse_options keyserver_opts[]=
70   {
71     /* some of these options are not real - just for the help
72        message */
73     {"max-cert-size",0,NULL,NULL},
74     {"include-revoked",0,NULL,N_("include revoked keys in search results")},
75     {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")},
76     {"use-temp-files",0,NULL,
77      N_("use temporary files to pass data to keyserver helpers")},
78     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL,
79      N_("do not delete temporary files after using them")},
80     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL,
81      NULL},
82     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL,
83      N_("automatically retrieve keys when verifying signatures")},
84     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL,
85      N_("honor the preferred keyserver URL set on the key")},
86     {"honor-pka-record",KEYSERVER_HONOR_PKA_RECORD,NULL,
87      N_("honor the PKA record set on a key when retrieving keys")},
88     {NULL,0,NULL,NULL}
89   };
90
91 static int keyserver_work(enum ks_action action,strlist_t list,
92                           KEYDB_SEARCH_DESC *desc,int count,
93                           unsigned char **fpr,size_t *fpr_len,
94                           struct keyserver_spec *keyserver);
95
96 /* Reasonable guess */
97 #define DEFAULT_MAX_CERT_SIZE 16384
98
99 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE;
100
101 static void
102 add_canonical_option(char *option,strlist_t *list)
103 {
104   char *arg=argsplit(option);
105
106   if(arg)
107     {
108       char *joined;
109
110       joined=xmalloc(strlen(option)+1+strlen(arg)+1);
111       /* Make a canonical name=value form with no spaces */
112       strcpy(joined,option);
113       strcat(joined,"=");
114       strcat(joined,arg);
115       append_to_strlist(list,joined);
116       xfree(joined);
117     }
118   else
119     append_to_strlist(list,option);
120 }
121
122 int
123 parse_keyserver_options(char *options)
124 {
125   int ret=1;
126   char *tok;
127   char *max_cert=NULL;
128
129   keyserver_opts[0].value=&max_cert;
130
131   while((tok=optsep(&options)))
132     {
133       if(tok[0]=='\0')
134         continue;
135
136       /* For backwards compatibility.  1.2.x used honor-http-proxy and
137          there are a good number of documents published that recommend
138          it. */
139       if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
140         tok="http-proxy";
141       else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
142         tok="no-http-proxy";
143
144       /* We accept quite a few possible options here - some options to
145          handle specially, the keyserver_options list, and import and
146          export options that pertain to keyserver operations.  Note
147          that you must use strncasecmp here as there might be an
148          =argument attached which will foil the use of strcasecmp. */
149
150 #ifdef EXEC_TEMPFILE_ONLY
151       if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
152               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
153         log_info(_("WARNING: keyserver option `%s' is not used"
154                    " on this platform\n"),tok);
155 #else
156       if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
157         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
158       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
159         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
160 #endif
161       else if(!parse_options(tok,&opt.keyserver_options.options,
162                              keyserver_opts,0)
163          && !parse_import_options(tok,
164                                   &opt.keyserver_options.import_options,0)
165          && !parse_export_options(tok,
166                                   &opt.keyserver_options.export_options,0))
167         {
168           /* All of the standard options have failed, so the option is
169              destined for a keyserver plugin. */
170           add_canonical_option(tok,&opt.keyserver_options.other);
171         }
172     }
173
174   if(max_cert)
175     {
176       max_cert_size=strtoul(max_cert,(char **)NULL,10);
177
178       if(max_cert_size==0)
179         max_cert_size=DEFAULT_MAX_CERT_SIZE;
180     }
181
182   return ret;
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 struct keyserver_spec *
239 parse_keyserver_uri(const char *string,int require_scheme,
240                     const char *configname,unsigned int configlineno)
241 {
242   int assume_hkp=0;
243   struct keyserver_spec *keyserver;
244   const char *idx;
245   int count;
246   char *uri,*options;
247
248   assert(string!=NULL);
249
250   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
251
252   uri=xstrdup(string);
253
254   options=strchr(uri,' ');
255   if(options)
256     {
257       char *tok;
258
259       *options='\0';
260       options++;
261
262       while((tok=optsep(&options)))
263         add_canonical_option(tok,&keyserver->options);
264     }
265
266   /* Get the scheme */
267
268   for(idx=uri,count=0;*idx && *idx!=':';idx++)
269     {
270       count++;
271
272       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
273          there clearly isn't a scheme so get out early. */
274       if(*idx=='[')
275         {
276           /* Was the '[' the first thing in the string?  If not, we
277              have a mangled scheme with a [ in it so fail. */
278           if(count==1)
279             break;
280           else
281             goto fail;
282         }
283     }
284
285   if(count==0)
286     goto fail;
287
288   if(*idx=='\0' || *idx=='[')
289     {
290       if(require_scheme)
291         return NULL;
292
293       /* Assume HKP if there is no scheme */
294       assume_hkp=1;
295       keyserver->scheme=xstrdup("hkp");
296
297       keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1);
298       strcpy(keyserver->uri,keyserver->scheme);
299       strcat(keyserver->uri,"://");
300       strcat(keyserver->uri,uri);
301     }
302   else
303     {
304       int i;
305
306       keyserver->uri=xstrdup(uri);
307
308       keyserver->scheme=xmalloc(count+1);
309
310       /* Force to lowercase */
311       for(i=0;i<count;i++)
312         keyserver->scheme[i]=ascii_tolower(uri[i]);
313
314       keyserver->scheme[i]='\0';
315
316       /* Skip past the scheme and colon */
317       uri+=count+1;
318     }
319
320   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
321     {
322       deprecated_warning(configname,configlineno,"x-broken-hkp",
323                          "--keyserver-options ","broken-http-proxy");
324       xfree(keyserver->scheme);
325       keyserver->scheme=xstrdup("hkp");
326       append_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
327     }
328   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
329     {
330       /* Canonicalize this to "hkp" so it works with both the internal
331          and external keyserver interface. */
332       xfree(keyserver->scheme);
333       keyserver->scheme=xstrdup("hkp");
334     }
335
336   if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/')
337     {
338       /* Three slashes means network path with a default host name.
339          This is a hack because it does not crok all possible
340          combiantions.  We should better repalce all code bythe parser
341          from http.c.  */
342       keyserver->path = xstrdup (uri+2);
343     }
344   else if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
345     {
346       /* Two slashes means network path. */
347
348       /* Skip over the "//", if any */
349       if(!assume_hkp)
350         uri+=2;
351
352       /* Do we have userinfo auth data present? */
353       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
354         count++;
355
356       /* We found a @ before the slash, so that means everything
357          before the @ is auth data. */
358       if(*idx=='@')
359         {
360           if(count==0)
361             goto fail;
362
363           keyserver->auth=xmalloc(count+1);
364           strncpy(keyserver->auth,uri,count);
365           keyserver->auth[count]='\0';
366           uri+=count+1;
367         }
368
369       /* Is it an RFC-2732 ipv6 [literal address] ? */
370       if(*uri=='[')
371         {
372           for(idx=uri+1,count=1;*idx
373                 && ((isascii (*idx) && isxdigit(*idx))
374                     || *idx==':' || *idx=='.');idx++)
375             count++;
376
377           /* Is the ipv6 literal address terminated? */
378           if(*idx==']')
379             count++;
380           else
381             goto fail;
382         }
383       else
384         for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
385           count++;
386
387       if(count==0)
388         goto fail;
389
390       keyserver->host=xmalloc(count+1);
391       strncpy(keyserver->host,uri,count);
392       keyserver->host[count]='\0';
393
394       /* Skip past the host */
395       uri+=count;
396
397       if(*uri==':')
398         {
399           /* It would seem to be reasonable to limit the range of the
400              ports to values between 1-65535, but RFC 1738 and 1808
401              imply there is no limit.  Of course, the real world has
402              limits. */
403
404           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
405             {
406               count++;
407
408               /* Ports are digits only */
409               if(!digitp(idx))
410                 goto fail;
411             }
412
413           keyserver->port=xmalloc(count+1);
414           strncpy(keyserver->port,uri+1,count);
415           keyserver->port[count]='\0';
416
417           /* Skip past the colon and port number */
418           uri+=1+count;
419         }
420
421       /* Everything else is the path */
422       if(*uri)
423         keyserver->path=xstrdup(uri);
424       else
425         keyserver->path=xstrdup("/");
426
427       if(keyserver->path[1])
428         keyserver->flags.direct_uri=1;
429     }
430   else if(uri[0]!='/')
431     {
432       /* No slash means opaque.  Just record the opaque blob and get
433          out. */
434       keyserver->opaque=xstrdup(uri);
435     }
436   else
437     {
438       /* One slash means absolute path.  We don't need to support that
439          yet. */
440       goto fail;
441     }
442
443   return keyserver;
444
445  fail:
446   free_keyserver_spec(keyserver);
447
448   return NULL;
449 }
450
451 struct keyserver_spec *
452 parse_preferred_keyserver(PKT_signature *sig)
453 {
454   struct keyserver_spec *spec=NULL;
455   const byte *p;
456   size_t plen;
457
458   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
459   if(p && plen)
460     {
461       byte *dupe=xmalloc(plen+1);
462
463       memcpy(dupe,p,plen);
464       dupe[plen]='\0';
465       spec=parse_keyserver_uri(dupe,1,NULL,0);
466       xfree(dupe);
467     }
468
469   return spec;
470 }
471
472 static void
473 print_keyrec(int number,struct keyrec *keyrec)
474 {
475   int i;
476
477   iobuf_writebyte(keyrec->uidbuf,0);
478   iobuf_flush_temp(keyrec->uidbuf);
479   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
480
481   if(keyrec->size>0)
482     printf("%d bit ",keyrec->size);
483
484   if(keyrec->type)
485     {
486       const char *str;
487
488       str = openpgp_pk_algo_name (keyrec->type);
489       if(str && strcmp (str, "?"))
490         printf("%s ",str);
491       else
492         printf("unknown ");
493     }
494
495   switch(keyrec->desc.mode)
496     {
497       /* If the keyserver helper gave us a short keyid, we have no
498          choice but to use it.  Do check --keyid-format to add a 0x if
499          needed. */
500     case KEYDB_SEARCH_MODE_SHORT_KID:
501       printf("key %s%08lX",
502              (opt.keyid_format==KF_0xSHORT
503               || opt.keyid_format==KF_0xLONG)?"0x":"",
504              (ulong)keyrec->desc.u.kid[1]);
505       break;
506
507       /* However, if it gave us a long keyid, we can honor
508          --keyid-format via keystr(). */
509     case KEYDB_SEARCH_MODE_LONG_KID:
510       printf("key %s",keystr(keyrec->desc.u.kid));
511       break;
512
513       /* If it gave us a PGP 2.x fingerprint, not much we can do
514          beyond displaying it. */
515     case KEYDB_SEARCH_MODE_FPR16:
516       printf("key ");
517       for(i=0;i<16;i++)
518         printf("%02X",keyrec->desc.u.fpr[i]);
519       break;
520
521       /* If we get a modern fingerprint, we have the most
522          flexibility. */
523     case KEYDB_SEARCH_MODE_FPR20:
524       {
525         u32 kid[2];
526         keyid_from_fingerprint(keyrec->desc.u.fpr,20,kid);
527         printf("key %s",keystr(kid));
528       }
529       break;
530
531     default:
532       BUG();
533       break;
534     }
535
536   if(keyrec->createtime>0)
537     {
538       printf(", ");
539       printf(_("created: %s"),strtimestamp(keyrec->createtime));
540     }
541
542   if(keyrec->expiretime>0)
543     {
544       printf(", ");
545       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
546     }
547
548   if(keyrec->flags&1)
549     printf(" (%s)",_("revoked"));
550   if(keyrec->flags&2)
551     printf(" (%s)",_("disabled"));
552   if(keyrec->flags&4)
553     printf(" (%s)",_("expired"));
554
555   printf("\n");
556 }
557
558 /* Returns a keyrec (which must be freed) once a key is complete, and
559    NULL otherwise.  Call with a NULL keystring once key parsing is
560    complete to return any unfinished keys. */
561 static struct keyrec *
562 parse_keyrec(char *keystring)
563 {
564   static struct keyrec *work=NULL;
565   struct keyrec *ret=NULL;
566   char *record;
567   int i;
568
569   if(keystring==NULL)
570     {
571       if(work==NULL)
572         return NULL;
573       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
574         {
575           xfree(work);
576           return NULL;
577         }
578       else
579         {
580           ret=work;
581           work=NULL;
582           return ret;
583         }
584     }
585
586   if(work==NULL)
587     {
588       work=xmalloc_clear(sizeof(struct keyrec));
589       work->uidbuf=iobuf_temp();
590     }
591
592   /* Remove trailing whitespace */
593   for(i=strlen(keystring);i>0;i--)
594     if(ascii_isspace(keystring[i-1]))
595       keystring[i-1]='\0';
596     else
597       break;
598
599   if((record=strsep(&keystring,":"))==NULL)
600     return ret;
601
602   if(ascii_strcasecmp("pub",record)==0)
603     {
604       char *tok;
605
606       if(work->desc.mode)
607         {
608           ret=work;
609           work=xmalloc_clear(sizeof(struct keyrec));
610           work->uidbuf=iobuf_temp();
611         }
612
613       if((tok=strsep(&keystring,":"))==NULL)
614         return ret;
615
616       classify_user_id(tok,&work->desc);
617       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
618          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
619          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
620          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
621         {
622           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
623           return ret;
624         }
625
626       /* Note all items after this are optional.  This allows us to
627          have a pub line as simple as pub:keyid and nothing else. */
628
629       work->lines++;
630
631       if((tok=strsep(&keystring,":"))==NULL)
632         return ret;
633
634       work->type=atoi(tok);
635
636       if((tok=strsep(&keystring,":"))==NULL)
637         return ret;
638
639       work->size=atoi(tok);
640
641       if((tok=strsep(&keystring,":"))==NULL)
642         return ret;
643
644       if(atoi(tok)<=0)
645         work->createtime=0;
646       else
647         work->createtime=atoi(tok);
648
649       if((tok=strsep(&keystring,":"))==NULL)
650         return ret;
651
652       if(atoi(tok)<=0)
653         work->expiretime=0;
654       else
655         {
656           work->expiretime=atoi(tok);
657           /* Force the 'e' flag on if this key is expired. */
658           if(work->expiretime<=make_timestamp())
659             work->flags|=4;
660         }
661
662       if((tok=strsep(&keystring,":"))==NULL)
663         return ret;
664
665       while(*tok)
666         switch(*tok++)
667           {
668           case 'r':
669           case 'R':
670             work->flags|=1;
671             break;
672
673           case 'd':
674           case 'D':
675             work->flags|=2;
676             break;
677
678           case 'e':
679           case 'E':
680             work->flags|=4;
681             break;
682           }
683     }
684   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
685     {
686       char *userid,*tok,*decoded;
687
688       if((tok=strsep(&keystring,":"))==NULL)
689         return ret;
690
691       if(strlen(tok)==0)
692         return ret;
693
694       userid=tok;
695
696       /* By definition, de-%-encoding is always smaller than the
697          original string so we can decode in place. */
698
699       i=0;
700
701       while(*tok)
702         if(tok[0]=='%' && tok[1] && tok[2])
703           {
704             int c;
705
706             userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
707             i++;
708             tok+=3;
709           }
710         else
711           userid[i++]=*tok++;
712
713       /* We don't care about the other info provided in the uid: line
714          since no keyserver supports marking userids with timestamps
715          or revoked/expired/disabled yet. */
716
717       /* No need to check for control characters, as utf8_to_native
718          does this for us. */
719
720       decoded=utf8_to_native(userid,i,0);
721       if(strlen(decoded)>opt.screen_columns-10)
722         decoded[opt.screen_columns-10]='\0';
723       iobuf_writestr(work->uidbuf,decoded);
724       xfree(decoded);
725       iobuf_writestr(work->uidbuf,"\n\t");
726       work->lines++;
727     }
728
729   /* Ignore any records other than "pri" and "uid" for easy future
730      growth. */
731
732   return ret;
733 }
734
735 /* TODO: do this as a list sent to keyserver_work rather than calling
736    it once for each key to get the correct counts after the import
737    (cosmetics, really) and to better take advantage of the keyservers
738    that can do multiple fetches in one go (LDAP). */
739 static int
740 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
741 {
742   char *answer;
743
744   fflush (stdout);
745
746   if(count && opt.command_fd==-1)
747     {
748       static int from=1;
749       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
750       from=numdesc+1;
751     }
752
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       printf("Q\n");
759       answer[0]='q';
760     }
761
762   if(answer[0]=='q' || answer[0]=='Q')
763     {
764       xfree(answer);
765       return 1;
766     }
767   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
768     {
769       char *split=answer,*num;
770
771       while((num=strsep(&split," ,"))!=NULL)
772         if(atoi(num)>=1 && atoi(num)<=numdesc)
773           keyserver_work(KS_GET,NULL,&desc[atoi(num)-1],1,
774                          NULL,NULL,opt.keyserver);
775
776       xfree(answer);
777       return 1;
778     }
779
780   return 0;
781 }
782
783 /* Count and searchstr are just for cosmetics.  If the count is too
784    small, it will grow safely.  If negative it disables the "Key x-y
785    of z" messages.  searchstr should be UTF-8 (rather than native). */
786 static void
787 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
788 {
789   int i=0,validcount=0,started=0,header=0,count=1;
790   unsigned int maxlen,buflen,numlines=0;
791   KEYDB_SEARCH_DESC *desc;
792   byte *line=NULL;
793   char *localstr=NULL;
794
795   if(searchstr)
796     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
797
798   desc=xmalloc(count*sizeof(KEYDB_SEARCH_DESC));
799
800   for(;;)
801     {
802       struct keyrec *keyrec;
803       int rl;
804
805       maxlen=1024;
806       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
807
808       if(opt.with_colons)
809         {
810           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
811              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
812             {
813               header=1;
814               continue;
815             }
816           else if(ascii_strncasecmp("SEARCH ",line,7)==0
817                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
818             continue;
819
820           printf("%s",line);
821         }
822
823       /* Look for an info: line.  The only current info: values
824          defined are the version and key count. */
825       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
826         {
827           char *tok,*str=&line[5];
828
829           if((tok=strsep(&str,":"))!=NULL)
830             {
831               int version;
832
833               if(sscanf(tok,"%d",&version)!=1)
834                 version=1;
835
836               if(version!=1)
837                 {
838                   log_error(_("invalid keyserver protocol "
839                               "(us %d!=handler %d)\n"),1,version);
840                   break;
841                 }
842             }
843
844           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
845             {
846               if(count==0)
847                 goto notfound;
848               else if(count<0)
849                 count=10;
850               else
851                 validcount=1;
852
853               desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
854             }
855
856           started=1;
857           continue;
858         }
859
860       if(rl==0)
861         {
862           keyrec=parse_keyrec(NULL);
863
864           if(keyrec==NULL)
865             {
866               if(i==0)
867                 {
868                   count=0;
869                   break;
870                 }
871
872               if(i!=count)
873                 validcount=0;
874
875               if (opt.with_colons && opt.batch)
876                 break;
877
878               for(;;)
879                 {
880                   if(show_prompt(desc,i,validcount?count:0,localstr))
881                     break;
882                   validcount=0;
883                 }
884
885               break;
886             }
887         }
888       else
889         keyrec=parse_keyrec(line);
890
891       if(i==count)
892         {
893           /* keyserver helper sent more keys than they claimed in the
894              info: line. */
895           count+=10;
896           desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
897           validcount=0;
898         }
899
900       if(keyrec)
901         {
902           desc[i]=keyrec->desc;
903
904           if(!opt.with_colons)
905             {
906               /* screen_lines - 1 for the prompt. */
907               if(numlines+keyrec->lines>opt.screen_lines-1)
908                 {
909                   if(show_prompt(desc,i,validcount?count:0,localstr))
910                     break;
911                   else
912                     numlines=0;
913                 }
914
915               print_keyrec(i+1,keyrec);
916             }
917
918           numlines+=keyrec->lines;
919           iobuf_close(keyrec->uidbuf);
920           xfree(keyrec);
921
922           started=1;
923           i++;
924         }
925     }
926
927  notfound:
928   /* Leave this commented out or now, and perhaps for a very long
929      time.  All HKPish servers return HTML error messages for
930      no-key-found. */
931   /*
932      if(!started)
933      log_info(_("keyserver does not support searching\n"));
934      else
935   */
936   if(count==0)
937     {
938       if(localstr)
939         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
940       else
941         log_info(_("key not found on keyserver\n"));
942     }
943
944   xfree(localstr);
945   xfree(desc);
946   xfree(line);
947 }
948
949 /* We sometimes want to use a different gpgkeys_xxx for a given
950    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
951    these here. */
952 static const char *
953 keyserver_typemap(const char *type)
954 {
955   if(strcmp(type,"ldaps")==0)
956     return "ldap";
957   else if(strcmp(type,"hkps")==0)
958     return "hkp";
959   else
960     return type;
961 }
962
963 /* The PGP LDAP and the curl fetch-a-LDAP-object methodologies are
964    sufficiently different that we can't use curl to do LDAP. */
965 static int
966 direct_uri_map(const char *scheme,unsigned int is_direct)
967 {
968   if(is_direct && strcmp(scheme,"ldap")==0)
969     return 1;
970
971   return 0;
972 }
973
974 #if GNUPG_MAJOR_VERSION == 2
975 #define GPGKEYS_PREFIX "gpg2keys_"
976 #else
977 #define GPGKEYS_PREFIX "gpgkeys_"
978 #endif
979 #define GPGKEYS_CURL GPGKEYS_PREFIX "curl" EXEEXT
980 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_CURL))
981 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
982 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
983
984 static int
985 keyserver_spawn(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
986                 int count,int *prog,unsigned char **fpr,size_t *fpr_len,
987                 struct keyserver_spec *keyserver)
988 {
989   int ret=0,i,gotversion=0,outofband=0;
990   strlist_t temp;
991   unsigned int maxlen,buflen;
992   char *command,*end,*searchstr=NULL;
993   byte *line=NULL;
994   struct exec_info *spawn;
995   const char *scheme;
996   const char *libexecdir = gnupg_libexecdir ();
997
998   assert(keyserver);
999
1000 #ifdef EXEC_TEMPFILE_ONLY
1001   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
1002 #endif
1003
1004   /* Build the filename for the helper to execute */
1005   scheme=keyserver_typemap(keyserver->scheme);
1006
1007 #ifdef DISABLE_KEYSERVER_PATH
1008   /* Destroy any path we might have.  This is a little tricky,
1009      portability-wise.  It's not correct to delete the PATH
1010      environment variable, as that may fall back to a system built-in
1011      PATH.  Similarly, it is not correct to set PATH to the null
1012      string (PATH="") since this actually deletes the PATH environment
1013      variable under MinGW.  The safest thing to do here is to force
1014      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
1015      Unix-like systems (since we're going to give a full path to
1016      gpgkeys_foo), but on W32 it prevents loading any DLLs from
1017      directories in %PATH%.
1018
1019      After some more thinking about this we came to the conclusion
1020      that it is better to load the helpers from the directory where
1021      the program of this process lives.  Fortunately Windows provides
1022      a way to retrieve this and our gnupg_libexecdir function has been
1023      modified to return just this.  Setting the exec-path is not
1024      anymore required.
1025        set_exec_path(libexecdir);
1026  */
1027 #else
1028   if(opt.exec_path_set)
1029     {
1030       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
1031          undefined, then don't specify a full path to gpgkeys_foo, so
1032          that the PATH can work. */
1033       command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1034       command[0]='\0';
1035     }
1036   else
1037 #endif
1038     {
1039       /* Specify a full path to gpgkeys_foo. */
1040       command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
1041                       GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1042       strcpy(command,libexecdir);
1043       strcat(command,DIRSEP_S);
1044     }
1045
1046   end=command+strlen(command);
1047
1048   /* Build a path for the keyserver helper.  If it is direct_uri
1049      (i.e. an object fetch and not a keyserver), then add "_uri" to
1050      the end to distinguish the keyserver helper from an object
1051      fetcher that can speak that protocol (this is a problem for
1052      LDAP). */
1053
1054   strcat(command,GPGKEYS_PREFIX);
1055   strcat(command,scheme);
1056
1057   /* This "_uri" thing is in case we need to call a direct handler
1058      instead of the keyserver handler.  This lets us use gpgkeys_curl
1059      or gpgkeys_ldap_uri (we don't provide it, but a user might)
1060      instead of gpgkeys_ldap to fetch things like
1061      ldap://keyserver.pgp.com/o=PGP%20keys?pgpkey?sub?pgpkeyid=99242560 */
1062
1063   if(direct_uri_map(scheme,keyserver->flags.direct_uri))
1064     strcat(command,"_uri");
1065
1066   strcat(command,EXEEXT);
1067
1068   /* Can we execute it?  If not, try curl as our catchall. */
1069   if(path_access(command,X_OK)!=0)
1070     strcpy(end,GPGKEYS_CURL);
1071
1072   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
1073     {
1074       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
1075         {
1076           command=xrealloc(command,strlen(command)+
1077                             strlen(KEYSERVER_ARGS_KEEP)+1);
1078           strcat(command,KEYSERVER_ARGS_KEEP);
1079         }
1080       else
1081         {
1082           command=xrealloc(command,strlen(command)+
1083                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
1084           strcat(command,KEYSERVER_ARGS_NOKEEP);
1085         }
1086
1087       ret=exec_write(&spawn,NULL,command,NULL,0,0);
1088     }
1089   else
1090     ret=exec_write(&spawn,command,NULL,NULL,0,0);
1091
1092   xfree(command);
1093
1094   if(ret)
1095     return ret;
1096
1097   fprintf(spawn->tochild,
1098           "# This is a GnuPG %s keyserver communications file\n",VERSION);
1099   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1100   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
1101   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
1102
1103   if(keyserver->opaque)
1104     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
1105   else
1106     {
1107       if(keyserver->auth)
1108         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
1109
1110       if(keyserver->host)
1111         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
1112
1113       if(keyserver->port)
1114         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
1115
1116       if(keyserver->path)
1117         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
1118     }
1119
1120   /* Write global options */
1121
1122   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
1123     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1124
1125   /* Write per-keyserver options */
1126
1127   for(temp=keyserver->options;temp;temp=temp->next)
1128     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1129
1130   switch(action)
1131     {
1132     case KS_GET:
1133       {
1134         fprintf(spawn->tochild,"COMMAND GET\n\n");
1135
1136         /* Which keys do we want? */
1137
1138         for(i=0;i<count;i++)
1139           {
1140             int quiet=0;
1141
1142             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
1143               {
1144                 int f;
1145
1146                 fprintf(spawn->tochild,"0x");
1147
1148                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
1149                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1150
1151                 fprintf(spawn->tochild,"\n");
1152               }
1153             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
1154               {
1155                 int f;
1156
1157                 fprintf(spawn->tochild,"0x");
1158
1159                 for(f=0;f<16;f++)
1160                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1161
1162                 fprintf(spawn->tochild,"\n");
1163               }
1164             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
1165               fprintf(spawn->tochild,"0x%08lX%08lX\n",
1166                       (ulong)desc[i].u.kid[0],
1167                       (ulong)desc[i].u.kid[1]);
1168             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
1169               fprintf(spawn->tochild,"0x%08lX\n",
1170                       (ulong)desc[i].u.kid[1]);
1171             else if(desc[i].mode==KEYDB_SEARCH_MODE_EXACT)
1172               {
1173                 fprintf(spawn->tochild,"0x0000000000000000\n");
1174                 quiet=1;
1175               }
1176             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
1177               continue;
1178             else
1179               BUG();
1180
1181             if(!quiet)
1182               {
1183                 if(keyserver->host)
1184                   log_info(_("requesting key %s from %s server %s\n"),
1185                            keystr_from_desc(&desc[i]),
1186                            keyserver->scheme,keyserver->host);
1187                 else
1188                   log_info(_("requesting key %s from %s\n"),
1189                            keystr_from_desc(&desc[i]),keyserver->uri);
1190               }
1191           }
1192
1193         fprintf(spawn->tochild,"\n");
1194
1195         break;
1196       }
1197
1198     case KS_GETNAME:
1199       {
1200         strlist_t key;
1201
1202         fprintf(spawn->tochild,"COMMAND GETNAME\n\n");
1203
1204         /* Which names do we want? */
1205
1206         for(key=list;key!=NULL;key=key->next)
1207           fprintf(spawn->tochild,"%s\n",key->d);
1208
1209         fprintf(spawn->tochild,"\n");
1210
1211         if(keyserver->host)
1212           log_info(_("searching for names from %s server %s\n"),
1213                    keyserver->scheme,keyserver->host);
1214         else
1215           log_info(_("searching for names from %s\n"),keyserver->uri);
1216
1217         break;
1218       }
1219
1220     case KS_SEND:
1221       {
1222         strlist_t key;
1223
1224         /* Note the extra \n here to send an empty keylist block */
1225         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1226
1227         for(key=list;key!=NULL;key=key->next)
1228           {
1229             armor_filter_context_t *afx;
1230             IOBUF buffer = iobuf_temp ();
1231             KBNODE block;
1232
1233             temp=NULL;
1234             add_to_strlist(&temp,key->d);
1235
1236             afx = new_armor_context ();
1237             afx->what = 1;
1238             /* Tell the armor filter to use Unix-style \n line
1239                endings, since we're going to fprintf this to a file
1240                that (on Win32) is open in text mode.  The win32 stdio
1241                will transform the \n to \r\n and we'll end up with the
1242                proper line endings on win32.  This is a no-op on
1243                Unix. */
1244             afx->eol[0] = '\n';
1245             push_armor_filter (afx, buffer);
1246             release_armor_context (afx);
1247
1248             /* TODO: Remove Comment: lines from keys exported this
1249                way? */
1250
1251             if(export_pubkeys_stream(buffer,temp,&block,
1252                                      opt.keyserver_options.export_options)==-1)
1253               iobuf_close(buffer);
1254             else
1255               {
1256                 KBNODE node;
1257
1258                 iobuf_flush_temp(buffer);
1259
1260                 merge_keys_and_selfsig(block);
1261
1262                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1263                         (ulong)block->pkt->pkt.public_key->keyid[0],
1264                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1265
1266                 for(node=block;node;node=node->next)
1267                   {
1268                     switch(node->pkt->pkttype)
1269                       {
1270                       default:
1271                         continue;
1272
1273                       case PKT_PUBLIC_KEY:
1274                       case PKT_PUBLIC_SUBKEY:
1275                         {
1276                           PKT_public_key *pk=node->pkt->pkt.public_key;
1277
1278                           keyid_from_pk(pk,NULL);
1279
1280                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1281                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1282                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1283                                   pk->pubkey_algo,
1284                                   nbits_from_pk(pk),
1285                                   pk->timestamp,
1286                                   pk->expiredate);
1287
1288                           if(pk->is_revoked)
1289                             fprintf(spawn->tochild,"r");
1290                           if(pk->has_expired)
1291                             fprintf(spawn->tochild,"e");
1292
1293                           fprintf(spawn->tochild,"\n");
1294                         }
1295                         break;
1296
1297                       case PKT_USER_ID:
1298                         {
1299                           PKT_user_id *uid=node->pkt->pkt.user_id;
1300                           int r;
1301
1302                           if(uid->attrib_data)
1303                             continue;
1304
1305                           fprintf(spawn->tochild,"uid:");
1306
1307                           /* Quote ':', '%', and any 8-bit
1308                              characters */
1309                           for(r=0;r<uid->len;r++)
1310                             {
1311                               if(uid->name[r]==':' || uid->name[r]=='%'
1312                                  || uid->name[r]&0x80)
1313                                 fprintf(spawn->tochild,"%%%02X",
1314                                         (byte)uid->name[r]);
1315                               else
1316                                 fprintf(spawn->tochild,"%c",uid->name[r]);
1317                             }
1318
1319                           fprintf(spawn->tochild,":%u:%u:",
1320                                   uid->created,uid->expiredate);
1321
1322                           if(uid->is_revoked)
1323                             fprintf(spawn->tochild,"r");
1324                           if(uid->is_expired)
1325                             fprintf(spawn->tochild,"e");
1326
1327                           fprintf(spawn->tochild,"\n");
1328                         }
1329                         break;
1330
1331                         /* This bit is really for the benefit of
1332                            people who store their keys in LDAP
1333                            servers.  It makes it easy to do queries
1334                            for things like "all keys signed by
1335                            Isabella". */
1336                       case PKT_SIGNATURE:
1337                         {
1338                           PKT_signature *sig=node->pkt->pkt.signature;
1339
1340                           if(!IS_UID_SIG(sig))
1341                             continue;
1342
1343                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1344                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1345                                   sig->sig_class,sig->timestamp,
1346                                   sig->expiredate);
1347                         }
1348                         break;
1349                       }
1350                   }
1351
1352                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1353                         (ulong)block->pkt->pkt.public_key->keyid[0],
1354                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1355
1356                 fprintf(spawn->tochild,"KEY %08lX%08lX BEGIN\n",
1357                         (ulong)block->pkt->pkt.public_key->keyid[0],
1358                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1359                 fwrite(iobuf_get_temp_buffer(buffer),
1360                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1361                 fprintf(spawn->tochild,"KEY %08lX%08lX END\n",
1362                         (ulong)block->pkt->pkt.public_key->keyid[0],
1363                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1364
1365                 iobuf_close(buffer);
1366
1367                 if(keyserver->host)
1368                   log_info(_("sending key %s to %s server %s\n"),
1369                            keystr(block->pkt->pkt.public_key->keyid),
1370                            keyserver->scheme,keyserver->host);
1371                 else
1372                   log_info(_("sending key %s to %s\n"),
1373                            keystr(block->pkt->pkt.public_key->keyid),
1374                            keyserver->uri);
1375
1376                 release_kbnode(block);
1377               }
1378
1379             free_strlist(temp);
1380           }
1381
1382         break;
1383       }
1384
1385     case KS_SEARCH:
1386       {
1387         strlist_t key;
1388
1389         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1390
1391         /* Which keys do we want?  Remember that the gpgkeys_ program
1392            is going to lump these together into a search string. */
1393
1394         for(key=list;key!=NULL;key=key->next)
1395           {
1396             fprintf(spawn->tochild,"%s\n",key->d);
1397             if(key!=list)
1398               {
1399                 searchstr=xrealloc(searchstr,
1400                                     strlen(searchstr)+strlen(key->d)+2);
1401                 strcat(searchstr," ");
1402               }
1403             else
1404               {
1405                 searchstr=xmalloc(strlen(key->d)+1);
1406                 searchstr[0]='\0';
1407               }
1408
1409             strcat(searchstr,key->d);
1410           }
1411
1412         fprintf(spawn->tochild,"\n");
1413
1414         if(keyserver->host)
1415           log_info(_("searching for \"%s\" from %s server %s\n"),
1416                    searchstr,keyserver->scheme,keyserver->host);
1417         else
1418           log_info(_("searching for \"%s\" from %s\n"),
1419                    searchstr,keyserver->uri);
1420
1421         break;
1422       }
1423
1424     default:
1425       log_fatal(_("no keyserver action!\n"));
1426       break;
1427     }
1428
1429   /* Done sending, so start reading. */
1430   ret=exec_read(spawn);
1431   if(ret)
1432     goto fail;
1433
1434   /* Now handle the response */
1435
1436   for(;;)
1437     {
1438       int plen;
1439       char *ptr;
1440
1441       maxlen=1024;
1442       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1443         {
1444           ret = gpg_error_from_syserror ();
1445           goto fail; /* i.e. EOF */
1446         }
1447
1448       ptr=line;
1449
1450       /* remove trailing whitespace */
1451       plen=strlen(ptr);
1452       while(plen>0 && ascii_isspace(ptr[plen-1]))
1453         plen--;
1454       plen[ptr]='\0';
1455
1456       if(*ptr=='\0')
1457         break;
1458
1459       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1460         {
1461           gotversion=1;
1462
1463           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1464             {
1465               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1466                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1467               goto fail;
1468             }
1469         }
1470       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1471         {
1472           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1473             log_info(_("WARNING: keyserver handler from a different"
1474                        " version of GnuPG (%s)\n"),&ptr[8]);
1475         }
1476       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1477         outofband=1; /* Currently the only OPTION */
1478     }
1479
1480   if(!gotversion)
1481     {
1482       log_error(_("keyserver did not send VERSION\n"));
1483       goto fail;
1484     }
1485
1486   if(!outofband)
1487     switch(action)
1488       {
1489       case KS_GET:
1490       case KS_GETNAME:
1491         {
1492           void *stats_handle;
1493
1494           stats_handle=import_new_stats_handle();
1495
1496           /* Slurp up all the key data.  In the future, it might be
1497              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1498              It's harmless to ignore them, but ignoring them does make
1499              gpg complain about "no valid OpenPGP data found".  One
1500              way to do this could be to continue parsing this
1501              line-by-line and make a temp iobuf for each key.  Note
1502              that we don't allow the import of secret keys from a
1503              keyserver.  Keyservers should never accept or send them
1504              but we better protect against rogue keyservers. */
1505
1506           import_keys_stream (spawn->fromchild, stats_handle, fpr, fpr_len,
1507                               (opt.keyserver_options.import_options
1508                                | IMPORT_NO_SECKEY));
1509
1510           import_print_stats(stats_handle);
1511           import_release_stats_handle(stats_handle);
1512
1513           break;
1514         }
1515
1516         /* Nothing to do here */
1517       case KS_SEND:
1518         break;
1519
1520       case KS_SEARCH:
1521         keyserver_search_prompt(spawn->fromchild,searchstr);
1522         break;
1523
1524       default:
1525         log_fatal(_("no keyserver action!\n"));
1526         break;
1527       }
1528
1529  fail:
1530   xfree(line);
1531   xfree(searchstr);
1532
1533
1534   *prog=exec_finish(spawn);
1535
1536   return ret;
1537 }
1538
1539 static int
1540 keyserver_work(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
1541                int count,unsigned char **fpr,size_t *fpr_len,
1542                struct keyserver_spec *keyserver)
1543 {
1544   int rc=0,ret=0;
1545
1546   if(!keyserver)
1547     {
1548       log_error(_("no keyserver known (use option --keyserver)\n"));
1549       return G10ERR_BAD_URI;
1550     }
1551
1552 #ifdef DISABLE_KEYSERVER_HELPERS
1553
1554   log_error(_("external keyserver calls are not supported in this build\n"));
1555   return G10ERR_KEYSERVER;
1556
1557 #else
1558   /* Spawn a handler */
1559
1560   rc=keyserver_spawn(action,list,desc,count,&ret,fpr,fpr_len,keyserver);
1561   if(ret)
1562     {
1563       switch(ret)
1564         {
1565         case KEYSERVER_SCHEME_NOT_FOUND:
1566           log_error(_("no handler for keyserver scheme `%s'\n"),
1567                     keyserver->scheme);
1568           break;
1569
1570         case KEYSERVER_NOT_SUPPORTED:
1571           log_error(_("action `%s' not supported with keyserver "
1572                       "scheme `%s'\n"),
1573                     action==KS_GET?"get":action==KS_SEND?"send":
1574                     action==KS_SEARCH?"search":"unknown",
1575                     keyserver->scheme);
1576           break;
1577
1578         case KEYSERVER_VERSION_ERROR:
1579           log_error(_(GPGKEYS_PREFIX "%s does not support"
1580                       " handler version %d\n"),
1581                     keyserver_typemap(keyserver->scheme),
1582                     KEYSERVER_PROTO_VERSION);
1583           break;
1584
1585         case KEYSERVER_TIMEOUT:
1586           log_error(_("keyserver timed out\n"));
1587           break;
1588
1589         case KEYSERVER_INTERNAL_ERROR:
1590         default:
1591           log_error(_("keyserver internal error\n"));
1592           break;
1593         }
1594
1595       return G10ERR_KEYSERVER;
1596     }
1597
1598   if(rc)
1599     {
1600       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1601
1602       return rc;
1603     }
1604
1605   return 0;
1606 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1607 }
1608
1609 int
1610 keyserver_export(strlist_t users)
1611 {
1612   strlist_t sl=NULL;
1613   KEYDB_SEARCH_DESC desc;
1614   int rc=0;
1615
1616   /* Weed out descriptors that we don't support sending */
1617   for(;users;users=users->next)
1618     {
1619       classify_user_id (users->d, &desc);
1620       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1621          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1622          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1623          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1624         {
1625           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1626           continue;
1627         }
1628       else
1629         append_to_strlist(&sl,users->d);
1630     }
1631
1632   if(sl)
1633     {
1634       rc=keyserver_work(KS_SEND,sl,NULL,0,NULL,NULL,opt.keyserver);
1635       free_strlist(sl);
1636     }
1637
1638   return rc;
1639 }
1640
1641 int
1642 keyserver_import(strlist_t users)
1643 {
1644   KEYDB_SEARCH_DESC *desc;
1645   int num=100,count=0;
1646   int rc=0;
1647
1648   /* Build a list of key ids */
1649   desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1650
1651   for(;users;users=users->next)
1652     {
1653       classify_user_id (users->d, &desc[count]);
1654       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1655          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1656          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1657          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1658         {
1659           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1660           continue;
1661         }
1662
1663       count++;
1664       if(count==num)
1665         {
1666           num+=100;
1667           desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1668         }
1669     }
1670
1671   if(count>0)
1672     rc=keyserver_work(KS_GET,NULL,desc,count,NULL,NULL,opt.keyserver);
1673
1674   xfree(desc);
1675
1676   return rc;
1677 }
1678
1679 int
1680 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1681                         struct keyserver_spec *keyserver)
1682 {
1683   KEYDB_SEARCH_DESC desc;
1684
1685   memset(&desc,0,sizeof(desc));
1686
1687   if(fprint_len==16)
1688     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1689   else if(fprint_len==20)
1690     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1691   else
1692     return -1;
1693
1694   memcpy(desc.u.fpr,fprint,fprint_len);
1695
1696   /* TODO: Warn here if the fingerprint we got doesn't match the one
1697      we asked for? */
1698   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1699 }
1700
1701 int
1702 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1703 {
1704   KEYDB_SEARCH_DESC desc;
1705
1706   memset(&desc,0,sizeof(desc));
1707
1708   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1709   desc.u.kid[0]=keyid[0];
1710   desc.u.kid[1]=keyid[1];
1711
1712   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1713 }
1714
1715 /* code mostly stolen from do_export_stream */
1716 static int
1717 keyidlist(strlist_t users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1718 {
1719   int rc=0,ndesc,num=100;
1720   KBNODE keyblock=NULL,node;
1721   KEYDB_HANDLE kdbhd;
1722   KEYDB_SEARCH_DESC *desc;
1723   strlist_t sl;
1724
1725   *count=0;
1726
1727   *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1728
1729   kdbhd=keydb_new(0);
1730
1731   if(!users)
1732     {
1733       ndesc = 1;
1734       desc = xmalloc_clear ( ndesc * sizeof *desc);
1735       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1736     }
1737   else
1738     {
1739       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1740         ;
1741       desc = xmalloc ( ndesc * sizeof *desc);
1742
1743       for (ndesc=0, sl=users; sl; sl = sl->next)
1744         {
1745           if(classify_user_id (sl->d, desc+ndesc))
1746             ndesc++;
1747           else
1748             log_error (_("key \"%s\" not found: %s\n"),
1749                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1750         }
1751     }
1752
1753   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1754     {
1755       if (!users)
1756         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1757
1758       /* read the keyblock */
1759       rc = keydb_get_keyblock (kdbhd, &keyblock );
1760       if( rc )
1761         {
1762           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1763           goto leave;
1764         }
1765
1766       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1767         {
1768           /* This is to work around a bug in some keyservers (pksd and
1769              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1770              The answer is to refresh both the correct v4 keyid
1771              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1772              This only happens for key refresh using the HKP scheme
1773              and if the refresh-add-fake-v3-keyids keyserver option is
1774              set. */
1775           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1776              node->pkt->pkt.public_key->version>=4)
1777             {
1778               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1779               v3_keyid (node->pkt->pkt.public_key->pkey[0],
1780                         (*klist)[*count].u.kid);
1781               (*count)++;
1782
1783               if(*count==num)
1784                 {
1785                   num+=100;
1786                   *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1787                 }
1788             }
1789
1790           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1791              This is because it's easy to calculate any sort of keyid
1792              from a v4 fingerprint, but not a v3 fingerprint. */
1793
1794           if(node->pkt->pkt.public_key->version<4)
1795             {
1796               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1797               keyid_from_pk(node->pkt->pkt.public_key,
1798                             (*klist)[*count].u.kid);
1799             }
1800           else
1801             {
1802               size_t dummy;
1803
1804               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1805               fingerprint_from_pk(node->pkt->pkt.public_key,
1806                                   (*klist)[*count].u.fpr,&dummy);
1807             }
1808
1809           /* This is a little hackish, using the skipfncvalue as a
1810              void* pointer to the keyserver spec, but we don't need
1811              the skipfnc here, and it saves having an additional field
1812              for this (which would be wasted space most of the
1813              time). */
1814
1815           (*klist)[*count].skipfncvalue=NULL;
1816
1817           /* Are we honoring preferred keyservers? */
1818           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1819             {
1820               PKT_user_id *uid=NULL;
1821               PKT_signature *sig=NULL;
1822
1823               merge_keys_and_selfsig(keyblock);
1824
1825               for(node=node->next;node;node=node->next)
1826                 {
1827                   if(node->pkt->pkttype==PKT_USER_ID
1828                      && node->pkt->pkt.user_id->is_primary)
1829                     uid=node->pkt->pkt.user_id;
1830                   else if(node->pkt->pkttype==PKT_SIGNATURE
1831                           && node->pkt->pkt.signature->
1832                           flags.chosen_selfsig && uid)
1833                     {
1834                       sig=node->pkt->pkt.signature;
1835                       break;
1836                     }
1837                 }
1838
1839               /* Try and parse the keyserver URL.  If it doesn't work,
1840                  then we end up writing NULL which indicates we are
1841                  the same as any other key. */
1842               if(sig)
1843                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1844             }
1845
1846           (*count)++;
1847
1848           if(*count==num)
1849             {
1850               num+=100;
1851               *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1852             }
1853         }
1854     }
1855
1856   if(rc==-1)
1857     rc=0;
1858
1859  leave:
1860   if(rc)
1861     xfree(*klist);
1862   xfree(desc);
1863   keydb_release(kdbhd);
1864   release_kbnode(keyblock);
1865
1866   return rc;
1867 }
1868
1869 /* Note this is different than the original HKP refresh.  It allows
1870    usernames to refresh only part of the keyring. */
1871
1872 int
1873 keyserver_refresh(strlist_t users)
1874 {
1875   int rc,count,numdesc,fakev3=0;
1876   KEYDB_SEARCH_DESC *desc;
1877   unsigned int options=opt.keyserver_options.import_options;
1878
1879   /* We switch merge-only on during a refresh, as 'refresh' should
1880      never import new keys, even if their keyids match. */
1881   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
1882
1883   /* Similarly, we switch on fast-import, since refresh may make
1884      multiple import sets (due to preferred keyserver URLs).  We don't
1885      want each set to rebuild the trustdb.  Instead we do it once at
1886      the end here. */
1887   opt.keyserver_options.import_options|=IMPORT_FAST;
1888
1889   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1890      scheme, then enable fake v3 keyid generation. */
1891   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1892      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1893          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1894     fakev3=1;
1895
1896   rc=keyidlist(users,&desc,&numdesc,fakev3);
1897   if(rc)
1898     return rc;
1899
1900   count=numdesc;
1901   if(count>0)
1902     {
1903       int i;
1904
1905       /* Try to handle preferred keyserver keys first */
1906       for(i=0;i<numdesc;i++)
1907         {
1908           if(desc[i].skipfncvalue)
1909             {
1910               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1911
1912               /* We use the keyserver structure we parsed out before.
1913                  Note that a preferred keyserver without a scheme://
1914                  will be interpreted as hkp:// */
1915
1916               rc=keyserver_work(KS_GET,NULL,&desc[i],1,NULL,NULL,keyserver);
1917               if(rc)
1918                 log_info(_("WARNING: unable to refresh key %s"
1919                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1920                          keyserver->uri,g10_errstr(rc));
1921               else
1922                 {
1923                   /* We got it, so mark it as NONE so we don't try and
1924                      get it again from the regular keyserver. */
1925
1926                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1927                   count--;
1928                 }
1929
1930               free_keyserver_spec(keyserver);
1931             }
1932         }
1933     }
1934
1935   if(count>0)
1936     {
1937       if(opt.keyserver)
1938         {
1939           if(count==1)
1940             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1941           else
1942             log_info(_("refreshing %d keys from %s\n"),
1943                      count,opt.keyserver->uri);
1944         }
1945
1946       rc=keyserver_work(KS_GET,NULL,desc,numdesc,NULL,NULL,opt.keyserver);
1947     }
1948
1949   xfree(desc);
1950
1951   opt.keyserver_options.import_options=options;
1952
1953   /* If the original options didn't have fast import, and the trustdb
1954      is dirty, rebuild. */
1955   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
1956     trustdb_check_or_update();
1957
1958   return rc;
1959 }
1960
1961 int
1962 keyserver_search(strlist_t tokens)
1963 {
1964   if(tokens)
1965     return keyserver_work(KS_SEARCH,tokens,NULL,0,NULL,NULL,opt.keyserver);
1966   else
1967     return 0;
1968 }
1969
1970 int
1971 keyserver_fetch(strlist_t urilist)
1972 {
1973   KEYDB_SEARCH_DESC desc;
1974   strlist_t sl;
1975   unsigned int options=opt.keyserver_options.import_options;
1976
1977   /* Switch on fast-import, since fetch can handle more than one
1978      import and we don't want each set to rebuild the trustdb.
1979      Instead we do it once at the end. */
1980   opt.keyserver_options.import_options|=IMPORT_FAST;
1981
1982   /* A dummy desc since we're not actually fetching a particular key
1983      ID */
1984   memset(&desc,0,sizeof(desc));
1985   desc.mode=KEYDB_SEARCH_MODE_EXACT;
1986
1987   for(sl=urilist;sl;sl=sl->next)
1988     {
1989       struct keyserver_spec *spec;
1990
1991       spec=parse_keyserver_uri(sl->d,1,NULL,0);
1992       if(spec)
1993         {
1994           int rc;
1995
1996           rc=keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,spec);
1997           if(rc)
1998             log_info (_("WARNING: unable to fetch URI %s: %s\n"),
1999                      sl->d,g10_errstr(rc));
2000
2001           free_keyserver_spec(spec);
2002         }
2003       else
2004         log_info (_("WARNING: unable to parse URI %s\n"),sl->d);
2005     }
2006
2007   opt.keyserver_options.import_options=options;
2008
2009   /* If the original options didn't have fast import, and the trustdb
2010      is dirty, rebuild. */
2011   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2012     trustdb_check_or_update();
2013
2014   return 0;
2015 }
2016
2017 /* Import key in a CERT or pointed to by a CERT */
2018 int
2019 keyserver_import_cert(const char *name,unsigned char **fpr,size_t *fpr_len)
2020 {
2021   char *domain,*look,*url;
2022   IOBUF key;
2023   int type,rc=G10ERR_GENERAL;
2024
2025   look=xstrdup(name);
2026
2027   domain=strrchr(look,'@');
2028   if(domain)
2029     *domain='.';
2030
2031   type=get_dns_cert(look,max_cert_size,&key,fpr,fpr_len,&url);
2032   if (!type || type == -1)
2033     {
2034       /* There might be an error in res_query which leads to an error
2035          return (-1) in the case that nothing was found.  Thus we take
2036          all errors as key not found.  */
2037       rc = G10ERR_NO_PUBKEY;
2038     }
2039   else if (type==1)
2040     {
2041       int armor_status=opt.no_armor;
2042
2043       /* CERTs are always in binary format */
2044       opt.no_armor=1;
2045
2046       rc=import_keys_stream (key, NULL, fpr, fpr_len,
2047                              (opt.keyserver_options.import_options
2048                               | IMPORT_NO_SECKEY));
2049
2050       opt.no_armor=armor_status;
2051
2052       iobuf_close(key);
2053     }
2054   else if(type==2 && *fpr)
2055     {
2056       /* We only consider the IPGP type if a fingerprint was provided.
2057          This lets us select the right key regardless of what a URL
2058          points to, or get the key from a keyserver. */
2059       if(url)
2060         {
2061           struct keyserver_spec *spec;
2062
2063           spec=parse_keyserver_uri(url,1,NULL,0);
2064           if(spec)
2065             {
2066               rc=keyserver_import_fprint(*fpr,*fpr_len,spec);
2067               free_keyserver_spec(spec);
2068             }
2069         }
2070       else if(opt.keyserver)
2071         {
2072           /* If only a fingerprint is provided, try and fetch it from
2073              our --keyserver */
2074
2075           rc=keyserver_import_fprint(*fpr,*fpr_len,opt.keyserver);
2076         }
2077       else
2078         log_info(_("no keyserver known (use option --keyserver)\n"));
2079
2080       /* Give a better string here? "CERT fingerprint for \"%s\"
2081          found, but no keyserver" " known (use option
2082          --keyserver)\n" ? */
2083
2084       xfree(url);
2085     }
2086
2087   xfree(look);
2088
2089   return rc;
2090 }
2091
2092 /* Import key pointed to by a PKA record. Return the requested
2093    fingerprint in fpr. */
2094 int
2095 keyserver_import_pka(const char *name,unsigned char **fpr,size_t *fpr_len)
2096 {
2097   char *uri;
2098   int rc = G10ERR_NO_PUBKEY;
2099
2100   *fpr = xmalloc (20);
2101   *fpr_len = 20;
2102
2103   uri = get_pka_info (name, *fpr);
2104   if (uri && *uri)
2105     {
2106       /* An URI is available.  Lookup the key. */
2107       struct keyserver_spec *spec;
2108       spec = parse_keyserver_uri (uri, 1, NULL, 0);
2109       if (spec)
2110         {
2111           rc = keyserver_import_fprint (*fpr, 20, spec);
2112           free_keyserver_spec (spec);
2113         }
2114       xfree (uri);
2115     }
2116
2117   if (rc)
2118     {
2119       xfree(*fpr);
2120       *fpr = NULL;
2121     }
2122
2123   return rc;
2124 }
2125
2126 /* Import all keys that match name */
2127 int
2128 keyserver_import_name(const char *name,unsigned char **fpr,size_t *fpr_len,
2129                       struct keyserver_spec *keyserver)
2130 {
2131   strlist_t list=NULL;
2132   int rc;
2133
2134   append_to_strlist(&list,name);
2135
2136   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2137
2138   free_strlist(list);
2139
2140   return rc;
2141 }
2142
2143 /* Import a key by name using LDAP */
2144 int
2145 keyserver_import_ldap(const char *name,unsigned char **fpr,size_t *fpr_len)
2146 {
2147   char *domain;
2148   struct keyserver_spec *keyserver;
2149   strlist_t list=NULL;
2150   int rc,hostlen=1;
2151 #ifdef USE_DNS_SRV
2152   struct srventry *srvlist=NULL;
2153   int srvcount,i;
2154   char srvname[MAXDNAME];
2155 #endif
2156
2157   /* Parse out the domain */
2158   domain=strrchr(name,'@');
2159   if(!domain)
2160     return G10ERR_GENERAL;
2161
2162   domain++;
2163
2164   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
2165   keyserver->scheme=xstrdup("ldap");
2166   keyserver->host=xmalloc(1);
2167   keyserver->host[0]='\0';
2168
2169 #ifdef USE_DNS_SRV
2170   snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
2171
2172   srvcount=getsrv(srvname,&srvlist);
2173
2174   for(i=0;i<srvcount;i++)
2175     {
2176       hostlen+=strlen(srvlist[i].target)+1;
2177       keyserver->host=xrealloc(keyserver->host,hostlen);
2178
2179       strcat(keyserver->host,srvlist[i].target);
2180
2181       if(srvlist[i].port!=389)
2182         {
2183           char port[7];
2184
2185           hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
2186           keyserver->host=xrealloc(keyserver->host,hostlen);
2187
2188           snprintf(port,7,":%u",srvlist[i].port);
2189           strcat(keyserver->host,port);
2190         }
2191
2192       strcat(keyserver->host," ");
2193     }
2194
2195   free(srvlist);
2196 #endif
2197
2198   /* If all else fails, do the PGP Universal trick of
2199      ldap://keys.(domain) */
2200
2201   hostlen+=5+strlen(domain);
2202   keyserver->host=xrealloc(keyserver->host,hostlen);
2203   strcat(keyserver->host,"keys.");
2204   strcat(keyserver->host,domain);
2205
2206   append_to_strlist(&list,name);
2207
2208   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2209
2210   free_strlist(list);
2211
2212   free_keyserver_spec(keyserver);
2213
2214   return rc;
2215 }